diff --git a/Cargo.lock b/Cargo.lock index 90b8301ea4..21aefd6900 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -599,6 +599,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1872,6 +1874,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -1915,6 +1923,7 @@ dependencies = [ "hyper", "hyper-util", "rustls", + "rustls-native-certs", "tokio", "tokio-rustls", "tower-service", @@ -2223,6 +2232,16 @@ dependencies = [ "jiff-tzdb", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -2638,6 +2657,44 @@ dependencies = [ "memchr", ] +[[package]] +name = "object_store" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622acbc9100d3c10e2ee15804b0caa40e55c933d5aa53814cd520805b7958a49" +dependencies = [ + "async-trait", + "base64 0.22.1", + "bytes", + "chrono", + "form_urlencoded", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body-util", + "humantime", + "hyper", + "itertools 0.14.0", + "md-5", + "parking_lot", + "percent-encoding", + "quick-xml", + "rand 0.10.3", + "reqwest", + "ring", + "serde", + "serde_json", + "serde_urlencoded", + "thiserror 2.0.21", + "tokio", + "tracing", + "url", + "walkdir", + "wasm-bindgen-futures", + "web-time", +] + [[package]] name = "oid-registry" version = "0.8.1" @@ -2710,6 +2767,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "openssl-src" version = "300.6.1+3.6.3" @@ -3213,6 +3276,16 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" +[[package]] +name = "quick-xml" +version = "0.39.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quinn" version = "0.11.12" @@ -3487,6 +3560,8 @@ dependencies = [ "base64 0.22.1", "bytes", "futures-core", + "futures-util", + "h2", "http", "http-body", "http-body-util", @@ -3499,6 +3574,7 @@ dependencies = [ "pin-project-lite", "quinn", "rustls", + "rustls-native-certs", "rustls-pki-types", "serde", "serde_json", @@ -3506,12 +3582,14 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-rustls", + "tokio-util", "tower", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", "webpki-roots 1.0.11", ] @@ -3721,6 +3799,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework 3.7.0", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -3785,6 +3875,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "0.9.0" @@ -4385,6 +4484,7 @@ dependencies = [ "flate2", "futures-util", "getrandom 0.4.3", + "object_store", "openidconnect", "proptest", "rcgen", @@ -4411,6 +4511,7 @@ dependencies = [ "tower-http", "utoipa", "uuid", + "zstd", ] [[package]] @@ -4563,6 +4664,7 @@ dependencies = [ "sqlbuild-sqltext", "sqlbuild-state", "stacker", + "tokio", "uuid", ] @@ -5741,6 +5843,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.107" @@ -6372,6 +6487,34 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zstd" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.3+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zvariant" version = "4.2.0" diff --git a/Cargo.toml b/Cargo.toml index 5b2453d6bc..627d06d190 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -157,6 +157,7 @@ rusqlite = { version = "0.37", features = ["bundled", "column_decltype"] } rustix = { version = "1.1.4", default-features = false, features = ["event", "fs", "process", "pty", "std", "stdio", "termios"] } saphyr-parser = "0.1" regex = "1" +object_store = { version = "0.13", default-features = false, features = ["fs", "aws"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1", features = ["derive"] } # Reports every field a decode ignores; a worker refuses a run request it can only partly read. @@ -170,6 +171,7 @@ chrono = { version = "0.4", features = ["serde"] } chrono-tz = "0.10" croner = "=3.0.1" flate2 = "1" +zstd = { version = "0.13", default-features = false } proptest = "1" same-file = "1" semver = "1" diff --git a/Makefile b/Makefile index 1b5cb187ea..6ced0ebdb9 100644 --- a/Makefile +++ b/Makefile @@ -135,6 +135,7 @@ E2E_DUCKDB_BUILD_CORE_PATHS := \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_dynamic_column_contract.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_dag_json_behavior.py \ + tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_enum_contract.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_execution_limits.py \ tests/e2e/src/sqlbuild/cli/commands/main/build/test_explicit_references.py \ diff --git a/clients/typescript/README.md b/clients/typescript/README.md index e21da1dd95..4ee7f14bc1 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -42,7 +42,7 @@ separate authentication contract, not an inferred privilege of this client. ## Authenticate through a trusted proxy Create a person with `sqb admin create-principal orders-reader`, then put the -returned `principal_id` in the `[trusted_proxy]` section of the server's +ID it prints (`principal_id` with `--json`) in the `[trusted_proxy]` section of the server's `server.toml`. Subjects are exact ASCII upstream identities, not inferred local usernames or email addresses: diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index 066fd0b112..fb4dc36314 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -80,6 +80,92 @@ export interface paths { patch?: never; trace?: never; }; + "/api/admin/service-accounts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Every service account by name with its working keys, never the keys themselves. Needs user.manage or role.assign. */ + get: operations["listServiceAccounts"]; + put?: never; + /** @description Adds a service account with a built-in role everywhere and returns its first key, only this once. Needs user.manage and role.assign. */ + post: operations["createServiceAccount"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/service-accounts/{principal_id}/disabled": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Disabling refuses every key of the account at once; enabling accepts the same keys again. Needs user.manage. */ + post: operations["setServiceAccountDisabled"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/service-accounts/{principal_id}/keys": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Issues a new key, returned only this once. The replaced key works on for overlap_minutes (at most 1440), else stops now; a key already in an overlap stops now. Needs user.manage. */ + post: operations["rotateServiceAccountKey"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/service-accounts/{principal_id}/keys/{key_id}/revoke": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Stops one working key now, such as an old key before its overlap ends. Needs user.manage. */ + post: operations["revokeServiceAccountKey"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/admin/service-accounts/{principal_id}/role": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Gives the account a built-in role everywhere in place of its other built-in roles everywhere. Needs role.assign. */ + post: operations["setServiceAccountRole"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/auth/cli/approve": { parameters: { query?: never; @@ -128,6 +214,23 @@ export interface paths { patch?: never; trace?: never; }; + "/api/auth/login-mode": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Answered only by a server without sign-in for people, so a browser or sqb login can say so instead of offering a password. */ + get: operations["readLoginMode"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/auth/logout": { parameters: { query?: never; @@ -466,6 +569,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/control/locations/{location_id}/targets/{target}/discovered": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readDiscovered"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/control/locations/{location_id}/targets/{target}/fingerprint": { parameters: { query?: never; @@ -754,6 +873,38 @@ export interface paths { patch?: never; trace?: never; }; + "/api/control/locations/{location_id}/targets/{target}/republish": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: operations["requestRepublish"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/control/locations/{location_id}/targets/{target}/republish/{request_id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readRepublish"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/control/locations/{location_id}/targets/{target}/runs": { parameters: { query?: never; @@ -866,6 +1017,70 @@ export interface paths { patch?: never; trace?: never; }; + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/download": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["downloadPersonRunOutput"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/index": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readPersonRunOutputIndex"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/lines": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readPersonRunOutputLines"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/search": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["searchPersonRunOutput"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/statements": { parameters: { query?: never; @@ -1554,6 +1769,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/runs/{run_id}/output/batches": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: operations["output_batch"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/runs/{run_id}/recall": { parameters: { query?: never; @@ -1591,7 +1822,7 @@ export interface components { * @description Closed permission vocabulary; unknown actions fail deserialization. * @enum {string} */ - Action: "view" | "view.sql" | "view.evidence" | "job.run" | "run.cancel" | "run.rerun" | "run.rewrite_history" | "run.prioritise" | "run.warehouse" | "run.vars" | "run.load" | "trigger.toggle" | "sensor.reset_cursor" | "run.adhoc" | "connection.test" | "user.manage" | "role.assign" | "audit.view"; + Action: "view" | "view.sql" | "view.evidence" | "job.run" | "run.cancel" | "run.rerun" | "run.rewrite_history" | "run.prioritise" | "run.warehouse" | "run.vars" | "run.load" | "trigger.toggle" | "sensor.reset_cursor" | "run.adhoc" | "connection.test" | "location.republish" | "user.manage" | "role.assign" | "audit.view"; /** @description What launching the command would run and whether this person may launch it. */ AdhocCheck: { /** @description Why the command cannot run regardless of permissions, such as a refused flag or an unknown selector. */ @@ -2050,6 +2281,52 @@ export interface components { /** @enum {string} */ status: "unavailable"; }; + /** @description The discovered sets of a target's current snapshot; empty when it saved none. */ + DiscoveredReadback: { + /** Format: int64 */ + generation: number; + /** Format: date-time */ + published_at: string; + sets: components["schemas"]["DiscoveredSetReadback"][]; + /** Format: uuid */ + snapshot_id: string; + }; + /** @description One discovered set of the current snapshot, as a deploy reads it back. */ + DiscoveredSetReadback: { + /** Format: int64 */ + check_every_seconds?: number | null; + digest?: string | null; + error?: string | null; + /** Format: date-time */ + fetched_at?: string | null; + /** Format: int64 */ + items: number; + /** Format: date-time */ + last_good_at?: string | null; + name: string; + status: components["schemas"]["DiscoveredSetStatus"]; + /** @description The tags of the result the set serves: its newest, or its last good one after a failure. */ + tags: Record; + }; + /** + * @description How a set's newest attempt went. + * @enum {string} + */ + DiscoveredSetStatus: "ok" | "failed" | "never"; + /** @description One discovered set as a location's health names it. */ + DiscoveryHealth: { + /** @description Why the newest attempt failed, secrets masked. */ + error?: string | null; + /** + * Format: int64 + * @description How many items the set serves: its newest result, or the last good one after a failure. + */ + items: number; + /** Format: date-time */ + last_good_at?: string | null; + name: string; + status: components["schemas"]["DiscoveredSetStatus"]; + }; /** @description A calendar whose pending past-due times a republish dropped, because its previous definition can't be read; it clears at its next successful tick. */ DroppedCalendarTimes: { /** Format: date-time */ @@ -2123,6 +2400,11 @@ export interface components { */ store_bytes: number; }; + /** @description A service account with a key that is returned only this once; the store keeps only its hash. */ + IssuedServiceKey: { + account: components["schemas"]["ServiceAccountSummary"]; + key: string; + }; /** @description One job or group as declared, for a person who may list the target; free-form setting values are withheld. */ JobDetailRecord: { /** @@ -2269,6 +2551,12 @@ export interface components { missing: number; /** @description Every provider missing a secret, including those the target allows; names only, never values. */ providers: components["schemas"]["MissingProviderSecrets"][]; + } | { + /** Format: int64 */ + generation: number; + /** @enum {string} */ + kind: "discovery"; + sets: components["schemas"]["DiscoveryHealth"][]; } | { /** Format: int64 */ generation: number; @@ -2361,6 +2649,11 @@ export interface components { kind: "plan"; selection: string[]; settings: Record; + } | { + /** @enum {string} */ + kind: "republish"; + /** @description The name of whoever asked, which the location prints with the request's reason. */ + requested_by: string; }; LocationWorkClaim: { /** Format: uuid */ @@ -2392,11 +2685,26 @@ export interface components { } | { /** @enum {string} */ kind: "sync_started"; + } | { + /** Format: int64 */ + generation: number; + /** @enum {string} */ + kind: "published"; + /** Format: uuid */ + snapshot_id: string; + } | { + error: string; + /** Format: int64 */ + generation: number; + /** @enum {string} */ + kind: "publish_failed"; } | { /** @enum {string} */ kind: "superseded"; }; LocationWorkPoll: { + /** @description Which work this poll takes. */ + scope: components["schemas"]["LocationWorkScope"]; /** Format: uuid */ session_id: string; target: string; @@ -2431,11 +2739,20 @@ export interface components { /** Format: uuid */ session_id: string; }; + /** + * @description Which work a location takes in one poll. + * @enum {string} + */ + LocationWorkScope: "all" | "republish_only"; /** * @description How people sign in to this server. * @enum {string} */ - LoginMode: "password" | "trusted_proxy" | "oidc" | "disabled"; + LoginMode: "password" | "trusted_proxy" | "oidc" | "disabled" | "keys"; + /** @description How a server without a session is signed in to, answered before sign-in only where people can't. */ + LoginModeAnswer: { + login_mode: components["schemas"]["LoginMode"]; + }; /** @description A running calendar schedule whose last date is at most a day away, or which has none left. */ LowCalendar: { /** @@ -2554,6 +2871,12 @@ export interface components { MutationResponse: { applied: boolean; }; + /** @description A service account to add: its name, what uses it, and its built-in role everywhere. */ + NewServiceAccount: { + description?: string | null; + name: string; + role: components["schemas"]["BuiltinRole"]; + }; /** @description One build's estimated query cost of one node, across every warehouse it used. */ NodeCostRecord: { /** Format: double */ @@ -2573,14 +2896,40 @@ export interface components { }; /** @enum {string} */ NodeEventKind: "success" | "failed" | "recovered"; - /** @enum {string} */ - NodeOutcome: "success" | "warn" | "failed" | "skipped" | "cancelled"; - /** @description One build attempt of a node by a run in this target; the same metadata as the run's node list. */ - NodeRunRecord: { + /** + * @description The level of a line a node logged with `ctx.log`. + * @enum {string} + */ + NodeLogLevel: "info" | "warning" | "error"; + /** @description One line a node logged with `ctx.log`. */ + NodeLogLine: { + level: string; /** Format: date-time */ - ended_at?: string | null; - error_code?: string | null; - job_key?: string | null; + logged_at: string; + message: string; + node_key: string; + }; + /** @enum {string} */ + NodeOutcome: "success" | "warn" | "failed" | "skipped" | "cancelled" | "not_run"; + /** @description How much one node printed: its lines, numbered across both streams, and its bytes. */ + NodeOutputSummary: { + /** Format: int64 */ + line_count: number; + /** @description The node key, or `run` for lines printed outside any node. */ + node_key: string; + /** Format: int64 */ + stderr_lines: number; + /** Format: int64 */ + stdout_lines: number; + /** Format: int64 */ + text_bytes: number; + }; + /** @description One build attempt of a node by a run in this target; the same metadata as the run's node list. */ + NodeRunRecord: { + /** Format: date-time */ + ended_at?: string | null; + error_code?: string | null; + job_key?: string | null; /** Format: date-time */ queued_at: string; /** Format: int64 */ @@ -2648,6 +2997,19 @@ export interface components { /** Format: int32 */ retry_delay_seconds: number; }; + /** @description What a worker printed in one batch window, a segment per node and stream in the order printed. */ + OutputBatch: { + /** + * Format: int64 + * @description The worker's batch number within its claim, from 0; a retried batch is stored once. + */ + batch: number; + segments: components["schemas"]["OutputSegment"][]; + }; + /** @description Whether the server stored a batch; a retry of a stored batch is not stored again. */ + OutputBatchReceipt: { + stored: boolean; + }; /** @description One exact-byte output chunk. */ OutputChunk: { /** @@ -2670,6 +3032,69 @@ export interface components { sequence: number; stream: components["schemas"]["OutputStream"]; }; + /** + * @description How a printed line reads: as an error or as a warning. + * @enum {string} + */ + OutputLevel: "error" | "warning"; + /** @description One stored line; lines a size cap left out just before it are counted on it. */ + OutputLine: { + /** + * Format: date-time + * @description When the server received the batch holding the line, within a few seconds of its printing. + */ + at: string; + level?: null | components["schemas"]["OutputLevel"]; + /** @description The node that printed it, or `run`. */ + node_key: string; + /** Format: int64 */ + number: number; + /** Format: int64 */ + omitted_before?: number; + stream: components["schemas"]["OutputStream"]; + text: string; + }; + /** @description A line that looks like an error, such as a traceback, or a warning; each stream keeps at most 10,000. */ + OutputMark: { + level: components["schemas"]["OutputLevel"]; + /** + * Format: int64 + * @description The line in the node's numbering. + */ + line: number; + stream: components["schemas"]["OutputStream"]; + /** @description The line's text, at most 300 bytes. */ + text: string; + }; + /** @description Rows covering lines `from` up to `to`, and where the pages before and after start. */ + OutputPage: { + /** + * Format: int64 + * @description The first line the rows cover. + */ + from: number; + /** + * Format: int64 + * @description The highest line number of the node, or of the run. + */ + line_count: number; + /** + * Format: int64 + * @description `from` for the next page, when there are later lines. + */ + next?: number | null; + /** + * Format: int64 + * @description `before` for the previous page, when there are earlier lines. + */ + previous?: number | null; + rows: components["schemas"]["OutputRow"][]; + /** + * Format: int64 + * @description The line after the last the rows cover. + */ + to: number; + }; /** @description Differing retries retain conflict evidence while preserving the first output bytes. */ OutputPublication: { /** Format: int32 */ @@ -2679,8 +3104,48 @@ export interface components { /** Format: int32 */ inserted: number; }; + /** @description A line, or a run of lines that are the same but for their numbers, folded into one row. */ + OutputRow: { + /** @enum {string} */ + kind: "line"; + line: components["schemas"]["OutputLine"]; + } | { + /** Format: int64 */ + count: number; + /** Format: int64 */ + from: number; + /** @enum {string} */ + kind: "similar"; + sample: components["schemas"]["OutputLine"]; + }; + /** @description The next match; across the whole output, how many match and which this is, when the output was small enough to scan; or where to continue. */ + OutputSearch: { + /** + * Format: int64 + * @description `from` for the next search in the same direction, when this one stopped before finding a match. + */ + continue_from?: number | null; + /** Format: int64 */ + count?: number | null; + /** Format: int64 */ + line?: number | null; + /** Format: int64 */ + rank?: number | null; + }; + /** @description Complete lines one node printed to one stream, each ending in a newline. */ + OutputSegment: { + /** + * Format: int64 + * @description Bytes the worker dropped just before these lines because it could not send them fast enough. + */ + dropped_bytes?: number; + /** @description The node that printed the lines, keyed `:`; `None` for lines printed outside a node. */ + node_key?: string | null; + stream: components["schemas"]["OutputStream"]; + text: string; + }; /** - * @description A process output stream. + * @description One process stream. * @enum {string} */ OutputStream: "stdout" | "stderr"; @@ -2802,6 +3267,8 @@ export interface components { skipped_by?: string | null; /** @description For each requested run the job's `skip` overlap dropped, the run that was active. */ skipped_for: string[]; + /** @description Why the tick's details are missing: an earlier release recorded them in a form this one can't read. */ + unreadable?: string | null; }; /** @description A run key is redacted and withheld like the custom cursor it usually derives from: empty without view.evidence. */ PersonSensorRunRequest: { @@ -3141,6 +3608,11 @@ export interface components { state_database?: string | null; state_schema: string; }; + /** + * @description A principal signs in as a person, or calls with an API key as a service account. + * @enum {string} + */ + PrincipalKind: "person" | "service"; /** @description Code that injects a provider: a node (`loader`, `asset`, `check`, `hook` or `materialization`, keyed `kind:name`), an `event_exporter` or a `sink`. */ ProviderConsumer: { kind: string; @@ -3305,6 +3777,33 @@ export interface components { /** Format: uuid */ trigger_id: string; }; + /** + * @description Where a republish request stands. + * @enum {string} + */ + RepublishState: "pending" | "published" | "failed" | "expired"; + /** @description A republish request and its result once the location has one. */ + RepublishStatus: { + /** Format: date-time */ + completed_at?: string | null; + error?: string | null; + /** Format: date-time */ + expires_at: string; + /** Format: int64 */ + generation?: number | null; + /** Format: uuid */ + location_id: string; + reason: string; + /** Format: uuid */ + request_id: string; + /** Format: date-time */ + requested_at: string; + requested_by: string; + /** Format: uuid */ + snapshot_id?: string | null; + state: components["schemas"]["RepublishState"]; + target: string; + }; /** @description A run a sensor's function asked for; the key defaults to the event ID and the job. */ RequestedRun: { job: string; @@ -3394,17 +3893,36 @@ export interface components { /** @enum {string} */ kind: "node_started"; node_key: string; + } | { + /** @enum {string} */ + kind: "node_progress"; + node_key: string; + /** Format: int64 */ + rows_so_far: number; + } | { + /** @enum {string} */ + kind: "node_log"; + level: components["schemas"]["NodeLogLevel"]; + message: string; + node_key: string; } | { error_code?: string | null; /** @description Redacted and bounded on the way in, whoever sends it; absent from older workers. */ error_message?: string | null; /** @enum {string} */ kind: "node_finished"; + /** @description Why a node that ran changed nothing. */ + no_change_reason?: string | null; node_key: string; outcome: components["schemas"]["NodeOutcome"]; /** Format: int64 */ rows_affected?: number | null; skipped_because_of?: string | null; + /** + * Format: int64 + * @description The rows a fully rebuilt table holds, where the warehouse's metadata count is exact. + */ + table_rows?: number | null; } | { /** @enum {string} */ kind: "check_started"; @@ -3476,6 +3994,12 @@ export interface components { RunEventRecord: { /** Format: int64 */ affected_rows?: number | null; + check_binding_key?: string | null; + /** @description For a check's result: its name as declared, its ID and this result's, and the rows it found; never its SQL or rows. */ + check_name?: string | null; + check_result_id?: string | null; + /** Format: int64 */ + check_rows?: number | null; /** Format: double */ duration_ms?: number | null; error_code?: string | null; @@ -3502,6 +4026,8 @@ export interface components { /** @description Workers compile locally and compare against this immutable snapshot, not the current deploy. */ RunExecution: { claim: components["schemas"]["RunClaim"]; + /** @description The discovered sets the run's snapshot saved, which the worker compiles from. */ + discovered: Record; environment_hash: string; node_hashes: { [key: string]: string; @@ -3551,13 +4077,32 @@ export interface components { /** Format: date-time */ ended_at?: string | null; error_code?: string | null; + /** @description The node's materialization in the run's snapshot, such as `table`, `incremental` or `view`. */ + materialization?: string | null; + /** @description For a node that failed unstarted because a provider was missing secrets, its redacted message naming the provider, variables and places looked; never other error text. */ + missing_secret?: string | null; + /** @description Why a node that ran changed nothing, such as `unchanged since its last build`. */ + no_change_reason?: string | null; node_key: string; - /** Format: int64 */ + /** + * Format: int64 + * @description Rows a statement inserted, merged or deleted, as the warehouse reported them. + */ rows_affected?: number | null; + /** + * Format: int64 + * @description Rows written so far while the node runs, from microbatch batches or a loader's progress. + */ + rows_so_far?: number | null; skipped_because_of?: string | null; /** Format: date-time */ started_at?: string | null; status: string; + /** + * Format: int64 + * @description The rows a fully rebuilt table holds, read from the warehouse's metadata where that count is exact. + */ + table_rows?: number | null; }; /** @enum {string} */ RunOrigin: "manual" | "schedule" | "sensor" | "rerun" | "backfill"; @@ -3573,6 +4118,31 @@ export interface components { /** @description The newest captured lines per invocation, oldest first. */ lines: components["schemas"]["RunOutputLine"][]; }; + /** @description What a run printed, per node, without its text; one node's error and warning lines; and what a size cap left out. */ + RunOutputIndex: { + /** + * Format: int64 + * @description Bytes the worker dropped because it could not send them fast enough. + */ + dropped_bytes: number; + /** + * Format: int64 + * @description Lines the whole run printed, numbered in the order printed. + */ + line_count: number; + /** @description Lines the run's nodes logged with `ctx.log`, oldest first. */ + logs: components["schemas"]["NodeLogLine"][]; + /** @description The named node's lines that look like errors or warnings, by line; empty when no node is named. */ + marks: components["schemas"]["OutputMark"][]; + nodes: components["schemas"]["NodeOutputSummary"][]; + /** + * Format: int64 + * @description Bytes and lines past `max_bytes_per_run` that were dropped between the run's first and last parts. + */ + omitted_bytes: number; + /** Format: int64 */ + omitted_lines: number; + }; RunOutputLine: { invocation_id: string; occurred_at: string; @@ -3665,6 +4235,11 @@ export interface components { }; /** @description The authorized selection and pinned execution inputs are immutable once requested. */ RunRequest: { + /** + * Format: uuid + * @description The first run of this run's rerun chain, read as `ctx.root_run_id`; unset for the first run. + */ + chain_run_id?: string | null; command?: components["schemas"]["RunCommand"]; image_id?: string | null; job_key?: string | null; @@ -3787,6 +4362,7 @@ export interface components { SecurityAuditEvent: { action: string; actor: string; + actor_kind?: null | components["schemas"]["PrincipalKind"]; /** @description The person's name when `actor` is a principal; person reads set it, exports leave it out. */ actor_name?: string | null; after_json: unknown; @@ -4096,6 +4672,67 @@ export interface components { scheduler: boolean; version: string; }; + ServiceAccountRole: { + role: components["schemas"]["BuiltinRole"]; + }; + ServiceAccountState: { + disabled: boolean; + }; + /** @description A service account as administrators see it: its role, state and working keys. */ + ServiceAccountSummary: { + /** Format: date-time */ + created_at: string; + created_by?: string | null; + description?: string | null; + /** + * Format: date-time + * @description While set, every key of the account is refused. + */ + disabled_at?: string | null; + /** @description Keys that work, or will once the account is enabled: the current key first, then one still in its overlap. */ + keys: components["schemas"]["ServiceKeySummary"][]; + /** + * Format: date-time + * @description The newest last use of any of its keys, stopped ones included. + */ + last_used_at?: string | null; + name: string; + /** Format: uuid */ + principal_id: string; + role?: null | components["schemas"]["BuiltinRole"]; + }; + /** + * @description How a service account key came to be: made by SQLBuild, or chosen with the CLI's `--key-from-env`. + * @enum {string} + */ + ServiceKeyOrigin: "issued" | "imported"; + /** @description A rotation: how many minutes the replaced key keeps working, at most a day; none or 0 stops it at once. */ + ServiceKeyRotation: { + /** Format: int64 */ + overlap_minutes?: number | null; + }; + /** @description One working key of a service account; never the key itself. */ + ServiceKeySummary: { + /** Format: date-time */ + created_at: string; + /** @description Who made it; none when the control-store owner did, with the CLI. */ + created_by?: string | null; + /** + * Format: date-time + * @description When a key replaced by a rotation stops working; none for the current key. + */ + expires_at?: string | null; + /** Format: uuid */ + key_id: string; + /** + * Format: date-time + * @description The last request this key authenticated that wasn't refused. + */ + last_used_at?: string | null; + origin: components["schemas"]["ServiceKeyOrigin"]; + /** @description The non-secret start of the key, e.g. `sqbk_Q7m2xT`. */ + prefix: string; + }; SessionIdentity: { /** Format: date-time */ expires_at: string; @@ -4800,45 +5437,53 @@ export interface operations { }; }; }; - approveCliLogin: { + listServiceAccounts: { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - requestBody: { - content: { - "application/json": components["schemas"]["CliLoginApprovalRequest"]; - }; - }; + requestBody?: never; responses: { - 204: { + 200: { headers: { [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["ServiceAccountSummary"][]; + }; }; + /** @description Session rejected */ 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AuthenticationDenial"]; + "application/json": components["schemas"]["ApiErrorBody"]; }; }; }; }; - claimCliLogin: { + createServiceAccount: { parameters: { query?: never; - header?: never; + header: { + /** @description Session CSRF token */ + "x-sqb-csrf": string; + }; path?: never; cookie?: never; }; requestBody: { content: { - "application/json": components["schemas"]["CliLoginClaimRequest"]; + "application/json": components["schemas"]["NewServiceAccount"]; }; }; responses: { @@ -4847,35 +5492,49 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["CliLoginSessionResponse"]; + "application/json": components["schemas"]["IssuedServiceKey"]; }; }; - 202: { + 400: { headers: { [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; }; + /** @description Session rejected */ 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AuthenticationDenial"]; + "application/json": components["schemas"]["ApiErrorBody"]; }; }; }; }; - startCliLogin: { + setServiceAccountDisabled: { parameters: { query?: never; - header?: never; - path?: never; + header: { + /** @description Session CSRF token */ + "x-sqb-csrf": string; + }; + path: { + principal_id: string; + }; cookie?: never; }; requestBody: { content: { - "application/json": components["schemas"]["CliLoginStartRequest"]; + "application/json": components["schemas"]["ServiceAccountState"]; }; }; responses: { @@ -4884,120 +5543,194 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["StartedLogin"]; + "application/json": components["schemas"]["ServiceAccountSummary"]; }; }; - 429: { + 400: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AuthenticationDenial"]; + "application/json": components["schemas"]["ApiErrorBody"]; }; }; - }; - }; - logoutSession: { - parameters: { - query?: never; - header: { - /** @description Session CSRF token */ - "x-sqb-csrf": string; - }; - path?: never; - cookie?: never; - }; - requestBody?: never; - responses: { - 204: { + /** @description Session rejected */ + 401: { headers: { [name: string]: unknown; }; content?: never; }; - 401: { + 403: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AuthenticationDenial"]; + "application/json": components["schemas"]["ApiErrorBody"]; }; }; }; }; - oidcIdentity: { + rotateServiceAccountKey: { parameters: { query?: never; - header?: never; - path?: never; + header: { + /** @description Session CSRF token */ + "x-sqb-csrf": string; + }; + path: { + principal_id: string; + }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["ServiceKeyRotation"]; + }; + }; responses: { 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ExternalIdentityResponse"]; + "application/json": components["schemas"]["IssuedServiceKey"]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; }; }; + /** @description Session rejected */ 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AuthenticationDenial"]; + "application/json": components["schemas"]["ApiErrorBody"]; }; }; }; }; - loginOidc: { + revokeServiceAccountKey: { parameters: { query?: never; - header?: never; - path?: never; + header: { + /** @description Session CSRF token */ + "x-sqb-csrf": string; + }; + path: { + principal_id: string; + key_id: string; + }; cookie?: never; }; requestBody?: never; responses: { - 303: { + 200: { headers: { [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["ServiceAccountSummary"]; + }; }; - 401: { + 400: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AuthenticationDenial"]; + "application/json": components["schemas"]["ApiErrorBody"]; }; }; - 429: { + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AuthenticationDenial"]; + "application/json": components["schemas"]["ApiErrorBody"]; }; }; }; }; - changePassword: { + setServiceAccountRole: { parameters: { query?: never; header: { /** @description Session CSRF token */ "x-sqb-csrf": string; }; + path: { + principal_id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["ServiceAccountRole"]; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ServiceAccountSummary"]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + approveCliLogin: { + parameters: { + query?: never; + header?: never; path?: never; cookie?: never; }; requestBody: { content: { - "application/json": components["schemas"]["PasswordChangeRequest"]; + "application/json": components["schemas"]["CliLoginApprovalRequest"]; }; }; responses: { @@ -5017,7 +5750,7 @@ export interface operations { }; }; }; - loginPassword: { + claimCliLogin: { parameters: { query?: never; header?: never; @@ -5026,7 +5759,7 @@ export interface operations { }; requestBody: { content: { - "application/json": components["schemas"]["PasswordLoginRequest"]; + "application/json": components["schemas"]["CliLoginClaimRequest"]; }; }; responses: { @@ -5035,8 +5768,14 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["PasswordSessionResponse"]; + "application/json": components["schemas"]["CliLoginSessionResponse"]; + }; + }; + 202: { + headers: { + [name: string]: unknown; }; + content?: never; }; 401: { headers: { @@ -5046,6 +5785,29 @@ export interface operations { "application/json": components["schemas"]["AuthenticationDenial"]; }; }; + }; + }; + startCliLogin: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["CliLoginStartRequest"]; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["StartedLogin"]; + }; + }; 429: { headers: { [name: string]: unknown; @@ -5056,7 +5818,33 @@ export interface operations { }; }; }; - createPasswordPerson: { + readLoginMode: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["LoginModeAnswer"]; + }; + }; + /** @description People sign in on this server */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + logoutSession: { parameters: { query?: never; header: { @@ -5066,27 +5854,65 @@ export interface operations { path?: never; cookie?: never; }; - requestBody: { - content: { - "application/json": components["schemas"]["PasswordPersonRequest"]; + requestBody?: never; + responses: { + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AuthenticationDenial"]; + }; }; }; + }; + oidcIdentity: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; responses: { 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["PersonCreated"]; + "application/json": components["schemas"]["ExternalIdentityResponse"]; }; }; - 400: { + 401: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiErrorBody"]; + "application/json": components["schemas"]["AuthenticationDenial"]; + }; + }; + }; + }; + loginOidc: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + 303: { + headers: { + [name: string]: unknown; }; + content?: never; }; 401: { headers: { @@ -5096,32 +5922,37 @@ export interface operations { "application/json": components["schemas"]["AuthenticationDenial"]; }; }; - 403: { + 429: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiErrorBody"]; + "application/json": components["schemas"]["AuthenticationDenial"]; }; }; }; }; - currentSession: { + changePassword: { parameters: { query?: never; - header?: never; + header: { + /** @description Session CSRF token */ + "x-sqb-csrf": string; + }; path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["PasswordChangeRequest"]; + }; + }; responses: { - 200: { + 204: { headers: { [name: string]: unknown; }; - content: { - "application/json": components["schemas"]["SessionIdentity"]; - }; + content?: never; }; 401: { headers: { @@ -5133,99 +5964,538 @@ export interface operations { }; }; }; - readSecurityAudit: { + loginPassword: { parameters: { - query?: { - /** @description Exclusive storage-order cursor */ - after?: number; - /** @description Exclusive upper cursor; when set, the page is newest first */ - before?: number; - limit?: number; + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["PasswordLoginRequest"]; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PasswordSessionResponse"]; + }; + }; + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AuthenticationDenial"]; + }; + }; + 429: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AuthenticationDenial"]; + }; + }; + }; + }; + createPasswordPerson: { + parameters: { + query?: never; + header: { + /** @description Session CSRF token */ + "x-sqb-csrf": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["PasswordPersonRequest"]; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PersonCreated"]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AuthenticationDenial"]; + }; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + currentSession: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["SessionIdentity"]; + }; + }; + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AuthenticationDenial"]; + }; + }; + }; + }; + readSecurityAudit: { + parameters: { + query?: { + /** @description Exclusive storage-order cursor */ + after?: number; + /** @description Exclusive upper cursor; when set, the page is newest first */ + before?: number; + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["SecurityAuditEvent"][]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + readBootstrap: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ControlBootstrap"]; + }; + }; + /** @description Session rejected or person disabled */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + listRunAcknowledgements: { + parameters: { + query?: never; + header?: never; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Runs marked handled in the last week */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["RunAcknowledgement"][]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + acknowledgeRun: { + parameters: { + query?: never; + header: { + "x-sqb-csrf": string; + }; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AcknowledgementRequest"]; + }; + }; + responses: { + /** @description Whether the run's acknowledgement changed */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MutationResponse"]; + }; + }; + /** @description The run is not in this location and target, or the event ID was reused */ + 400: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + listAttentionAcknowledgements: { + parameters: { + query?: never; + header?: never; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Conditions marked handled within two snoozes, lapsed ones included, and the snooze */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AttentionAcknowledgements"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + acknowledgeAttention: { + parameters: { + query?: never; + header: { + "x-sqb-csrf": string; + }; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AttentionAcknowledgementRequest"]; + }; + }; + responses: { + /** @description Whether the condition's acknowledgement changed */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MutationResponse"]; + }; + }; + /** @description The key, shape or reason is invalid, or the event ID was reused */ + 400: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + readPersonCatalog: { + parameters: { + query: { + /** @description Exact database; omitted matches SQL NULL */ + database?: string; + /** @description Exact physical schema */ + schema: string; + after_observed_at?: string; + after_event_id?: string; + /** @description Page size; defaults to 100, clamped to 1..100 */ + limit?: number; + }; + header?: never; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["CatalogPage"]; + }; + }; + /** @description Invalid namespace or cursor */ + 400: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; + subscribeChanges: { + parameters: { + query?: never; + header?: never; + path: { + location_id: string; + target: string; }; - header?: never; - path?: never; cookie?: never; }; requestBody?: never; responses: { + /** @description changed events: all, runs, ticks, snapshot:, node_status:. Refetch REST on all/reconnect; no durable cursor. node_status carries version, previous_version and the changed states (empty when none changed), or full: refetch node states when full is set or previous_version is not the version held. */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["SecurityAuditEvent"][]; - }; - }; - 400: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": components["schemas"]["ApiErrorBody"]; + "text/event-stream": components["schemas"]["ChangeNotice"]; }; }; - /** @description Session rejected */ + /** @description Session rejected or person disabled */ 401: { headers: { [name: string]: unknown; }; content?: never; }; + /** @description View does not cover every node of this target */ 403: { headers: { [name: string]: unknown; }; - content: { - "application/json": components["schemas"]["ApiErrorBody"]; - }; + content?: never; }; }; }; - readBootstrap: { + listPersonChecks: { parameters: { query?: never; - header?: never; - path?: never; + header?: { + /** @description An ETag from an earlier response; 304 while every check's newest result is unchanged */ + "If-None-Match"?: string | null; + }; + path: { + location_id: string; + target: string; + }; cookie?: never; }; requestBody?: never; responses: { + /** @description The newest result of every check */ 200: { headers: { + /** @description ":", or "" before the first publication */ + ETag?: string; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ControlBootstrap"]; + "application/json": components["schemas"]["CheckResult"][]; }; }; - /** @description Session rejected or person disabled */ + /** @description Unchanged since the If-None-Match ETag */ + 304: { + headers: { + ETag?: string; + [name: string]: unknown; + }; + content?: never; + }; + /** @description Session rejected */ 401: { headers: { [name: string]: unknown; }; content?: never; }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; }; }; - listRunAcknowledgements: { + readPersonCheckHistory: { parameters: { - query?: never; + query?: { + /** @description Maximum results, newest first; defaults to 50, capped at 1000 */ + limit?: number; + }; header?: never; path: { location_id: string; target: string; + binding_key: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Runs marked handled in the last week */ + /** @description Empty for an unknown check */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["RunAcknowledgement"][]; + "application/json": components["schemas"]["CheckResult"][]; }; }; /** @description Session rejected */ @@ -5245,39 +6515,27 @@ export interface operations { }; }; }; - acknowledgeRun: { + readPersonCheckEvidence: { parameters: { query?: never; - header: { - "x-sqb-csrf": string; - }; + header?: never; path: { location_id: string; target: string; + binding_key: string; + event_id: string; }; cookie?: never; }; - requestBody: { - content: { - "application/json": components["schemas"]["AcknowledgementRequest"]; - }; - }; + requestBody?: never; responses: { - /** @description Whether the run's acknowledgement changed */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["MutationResponse"]; - }; - }; - /** @description The run is not in this location and target, or the event ID was reused */ - 400: { - headers: { - [name: string]: unknown; + "application/json": null | components["schemas"]["CheckEvidence"]; }; - content?: never; }; /** @description Session rejected */ 401: { @@ -5296,25 +6554,25 @@ export interface operations { }; }; }; - listAttentionAcknowledgements: { + readPersonCheckSql: { parameters: { query?: never; header?: never; path: { location_id: string; target: string; + binding_key: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Conditions marked handled within two snoozes, lapsed ones included, and the snooze */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AttentionAcknowledgements"]; + "application/json": null | components["schemas"]["CheckSql"]; }; }; /** @description Session rejected */ @@ -5334,39 +6592,28 @@ export interface operations { }; }; }; - acknowledgeAttention: { + readPersonColumnLineage: { parameters: { - query?: never; - header: { - "x-sqb-csrf": string; + query: { + /** @description The node whose upstream and downstream column lineage to return */ + node_key: string; }; + header?: never; path: { location_id: string; target: string; }; cookie?: never; }; - requestBody: { - content: { - "application/json": components["schemas"]["AttentionAcknowledgementRequest"]; - }; - }; + requestBody?: never; responses: { - /** @description Whether the condition's acknowledgement changed */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["MutationResponse"]; - }; - }; - /** @description The key, shape or reason is invalid, or the event ID was reused */ - 400: { - headers: { - [name: string]: unknown; + "application/json": components["schemas"]["ColumnLineageRead"]; }; - content?: never; }; /** @description Session rejected */ 401: { @@ -5385,41 +6632,39 @@ export interface operations { }; }; }; - readPersonCatalog: { + requestConnectionTest: { parameters: { - query: { - /** @description Exact database; omitted matches SQL NULL */ - database?: string; - /** @description Exact physical schema */ - schema: string; - after_observed_at?: string; - after_event_id?: string; - /** @description Page size; defaults to 100, clamped to 1..100 */ - limit?: number; + query?: never; + header: { + "x-sqb-csrf": string; }; - header?: never; path: { location_id: string; target: string; }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["PersonWorkRequest"]; + }; + }; responses: { 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["CatalogPage"]; + "application/json": components["schemas"]["MutationResponse"]; }; }; - /** @description Invalid namespace or cursor */ 400: { headers: { [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; }; /** @description Session rejected */ 401: { @@ -5438,50 +6683,51 @@ export interface operations { }; }; }; - subscribeChanges: { + readConnectionTest: { parameters: { query?: never; header?: never; path: { location_id: string; target: string; + request_id: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description changed events: all, runs, ticks, snapshot:, node_status:. Refetch REST on all/reconnect; no durable cursor. node_status carries version, previous_version and the changed states (empty when none changed), or full: refetch node states when full is set or previous_version is not the version held. */ 200: { headers: { [name: string]: unknown; }; content: { - "text/event-stream": components["schemas"]["ChangeNotice"]; + "application/json": null | components["schemas"]["LocationWorkRecord"]; }; }; - /** @description Session rejected or person disabled */ + /** @description Session rejected */ 401: { headers: { [name: string]: unknown; }; content?: never; }; - /** @description View does not cover every node of this target */ 403: { headers: { [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; }; }; }; - listPersonChecks: { + readPersonCostSummary: { parameters: { - query?: never; - header?: { - /** @description An ETag from an earlier response; 304 while every check's newest result is unchanged */ - "If-None-Match"?: string | null; + query?: { + /** @description Runs that started in the last this many days; defaults to 7, capped at 90 */ + days?: number; }; + header?: never; path: { location_id: string; target: string; @@ -5490,24 +6736,14 @@ export interface operations { }; requestBody?: never; responses: { - /** @description The newest result of every check */ + /** @description Estimated query cost by job, warehouse size and node, most expensive first */ 200: { headers: { - /** @description ":", or "" before the first publication */ - ETag?: string; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["CheckResult"][]; - }; - }; - /** @description Unchanged since the If-None-Match ETag */ - 304: { - headers: { - ETag?: string; - [name: string]: unknown; + "application/json": components["schemas"]["CostSummaryRecord"]; }; - content?: never; }; /** @description Session rejected */ 401: { @@ -5526,29 +6762,24 @@ export interface operations { }; }; }; - readPersonCheckHistory: { + readDiscovered: { parameters: { - query?: { - /** @description Maximum results, newest first; defaults to 50, capped at 1000 */ - limit?: number; - }; + query?: never; header?: never; path: { location_id: string; target: string; - binding_key: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Empty for an unknown check */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["CheckResult"][]; + "application/json": null | components["schemas"]["DiscoveredReadback"]; }; }; /** @description Session rejected */ @@ -5568,15 +6799,22 @@ export interface operations { }; }; }; - readPersonCheckEvidence: { + readPersonFingerprint: { parameters: { - query?: never; + query: { + node_type: string; + node_name: string; + /** @description Exact destination database; omitted matches SQL NULL */ + database?: string; + /** @description Exact destination schema; omitted matches SQL NULL */ + schema?: string; + /** @description Exact destination name; omitted matches SQL NULL */ + name?: string; + }; header?: never; path: { location_id: string; target: string; - binding_key: string; - event_id: string; }; cookie?: never; }; @@ -5587,8 +6825,15 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["CheckEvidence"]; + "application/json": null | components["schemas"]["FingerprintObservation"]; + }; + }; + /** @description Invalid node */ + 400: { + headers: { + [name: string]: unknown; }; + content?: never; }; /** @description Session rejected */ 401: { @@ -5607,25 +6852,25 @@ export interface operations { }; }; }; - readPersonCheckSql: { + readPersonLocationHealth: { parameters: { query?: never; header?: never; path: { location_id: string; target: string; - binding_key: string; }; cookie?: never; }; requestBody?: never; responses: { + /** @description This target's newest health observations and instance check-ins */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["CheckSql"]; + "application/json": components["schemas"]["LocationHealthObservation"][]; }; }; /** @description Session rejected */ @@ -5645,12 +6890,9 @@ export interface operations { }; }; }; - readPersonColumnLineage: { + listPersonJobs: { parameters: { - query: { - /** @description The node whose upstream and downstream column lineage to return */ - node_key: string; - }; + query?: never; header?: never; path: { location_id: string; @@ -5665,7 +6907,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ColumnLineageRead"]; + "application/json": components["schemas"]["JobRecord"][]; }; }; /** @description Session rejected */ @@ -5685,38 +6927,25 @@ export interface operations { }; }; }; - requestConnectionTest: { + readPersonJob: { parameters: { query?: never; - header: { - "x-sqb-csrf": string; - }; + header?: never; path: { location_id: string; target: string; + job_key: string; }; cookie?: never; }; - requestBody: { - content: { - "application/json": components["schemas"]["PersonWorkRequest"]; - }; - }; + requestBody?: never; responses: { 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["MutationResponse"]; - }; - }; - 400: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": components["schemas"]["ApiErrorBody"]; + "application/json": components["schemas"]["JobDetailRecord"]; }; }; /** @description Session rejected */ @@ -5726,6 +6955,7 @@ export interface operations { }; content?: never; }; + /** @description Needs view on every current node of the target */ 403: { headers: { [name: string]: unknown; @@ -5734,16 +6964,27 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; + /** @description No published job by that name */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; - readConnectionTest: { + readPersonMaintenance: { parameters: { - query?: never; + query?: { + /** @description Only moves into this model, and no janitor events */ + node?: string; + /** @description Maximum moves and janitor events each; defaults to 100, capped at 1000 */ + limit?: number; + }; header?: never; path: { location_id: string; target: string; - request_id: string; }; cookie?: never; }; @@ -5754,7 +6995,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["LocationWorkRecord"]; + "application/json": components["schemas"]["MaintenanceHistory"]; }; }; /** @description Session rejected */ @@ -5774,28 +7015,29 @@ export interface operations { }; }; }; - readPersonCostSummary: { + readPersonMicrobatchCoverage: { parameters: { query?: { - /** @description Runs that started in the last this many days; defaults to 7, capped at 90 */ - days?: number; + /** @description Maximum newest batches; defaults to 200, capped at 1000 */ + limit?: number; }; header?: never; path: { location_id: string; target: string; + model: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Estimated query cost by job, warehouse size and node, most expensive first */ + /** @description Null when the model has no tracked coverage */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["CostSummaryRecord"]; + "application/json": null | components["schemas"]["MicrobatchCoverage"]; }; }; /** @description Session rejected */ @@ -5815,18 +7057,9 @@ export interface operations { }; }; }; - readPersonFingerprint: { + readPersonNodeStates: { parameters: { - query: { - node_type: string; - node_name: string; - /** @description Exact destination database; omitted matches SQL NULL */ - database?: string; - /** @description Exact destination schema; omitted matches SQL NULL */ - schema?: string; - /** @description Exact destination name; omitted matches SQL NULL */ - name?: string; - }; + query?: never; header?: never; path: { location_id: string; @@ -5836,20 +7069,14 @@ export interface operations { }; requestBody?: never; responses: { + /** @description Every current node's state at the state version node_status events continue from */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["FingerprintObservation"]; - }; - }; - /** @description Invalid node */ - 400: { - headers: { - [name: string]: unknown; + "application/json": components["schemas"]["NodeStatesRecord"]; }; - content?: never; }; /** @description Session rejected */ 401: { @@ -5868,9 +7095,12 @@ export interface operations { }; }; }; - readPersonLocationHealth: { + readPersonNodeStatus: { parameters: { - query?: never; + query: { + /** @description One exact published node key */ + node_key: string; + }; header?: never; path: { location_id: string; @@ -5880,14 +7110,20 @@ export interface operations { }; requestBody?: never; responses: { - /** @description This target's newest health observations and instance check-ins */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["LocationHealthObservation"][]; + "application/json": null | components["schemas"]["NodeStatus"]; + }; + }; + /** @description Invalid node key */ + 400: { + headers: { + [name: string]: unknown; }; + content?: never; }; /** @description Session rejected */ 401: { @@ -5906,10 +7142,13 @@ export interface operations { }; }; }; - listPersonJobs: { + listPersonCatalogNodes: { parameters: { query?: never; - header?: never; + header?: { + /** @description An ETag from an earlier response; 304 when the snapshot is unchanged */ + "If-None-Match"?: string | null; + }; path: { location_id: string; target: string; @@ -5918,13 +7157,24 @@ export interface operations { }; requestBody?: never; responses: { + /** @description Every node of the current snapshot without its state, which node-states serves; empty before the first publication */ 200: { headers: { + /** @description ""; absent before the first publication */ + ETag?: string; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["JobRecord"][]; + "application/json": components["schemas"]["CatalogNodeRecord"][]; + }; + }; + /** @description Unchanged since the If-None-Match ETag */ + 304: { + headers: { + ETag?: string; + [name: string]: unknown; }; + content?: never; }; /** @description Session rejected */ 401: { @@ -5943,25 +7193,31 @@ export interface operations { }; }; }; - readPersonJob: { + listPersonNodeCosts: { parameters: { - query?: never; + query?: { + /** @description Builds that started in the last this many days; defaults to 7, capped at 90 */ + days?: number; + /** @description Maximum builds; defaults to 100, capped at 1000 */ + limit?: number; + }; header?: never; path: { location_id: string; target: string; - job_key: string; + node_key: string; }; cookie?: never; }; requestBody?: never; responses: { + /** @description The node's estimated query cost in each build, newest first */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["JobDetailRecord"]; + "application/json": components["schemas"]["NodeCostRecord"][]; }; }; /** @description Session rejected */ @@ -5971,7 +7227,6 @@ export interface operations { }; content?: never; }; - /** @description Needs view on every current node of the target */ 403: { headers: { [name: string]: unknown; @@ -5980,38 +7235,31 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; - /** @description No published job by that name */ - 404: { - headers: { - [name: string]: unknown; - }; - content?: never; - }; }; }; - readPersonMaintenance: { + listPersonNodeRuns: { parameters: { query?: { - /** @description Only moves into this model, and no janitor events */ - node?: string; - /** @description Maximum moves and janitor events each; defaults to 100, capped at 1000 */ + /** @description Maximum recent runs; defaults to 100, capped at 1000 */ limit?: number; }; header?: never; path: { location_id: string; target: string; + node_key: string; }; cookie?: never; }; requestBody?: never; responses: { + /** @description Runs that built the node, newest first */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["MaintenanceHistory"]; + "application/json": components["schemas"]["NodeRunRecord"][]; }; }; /** @description Session rejected */ @@ -6031,29 +7279,25 @@ export interface operations { }; }; }; - readPersonMicrobatchCoverage: { + readPersonNodeSql: { parameters: { - query?: { - /** @description Maximum newest batches; defaults to 200, capped at 1000 */ - limit?: number; - }; + query?: never; header?: never; path: { location_id: string; target: string; - model: string; + node_key: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Null when the model has no tracked coverage */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["MicrobatchCoverage"]; + "application/json": null | components["schemas"]["NodeSql"]; }; }; /** @description Session rejected */ @@ -6073,25 +7317,38 @@ export interface operations { }; }; }; - readPersonNodeStates: { + requestPlan: { parameters: { query?: never; - header?: never; + header: { + "x-sqb-csrf": string; + }; path: { location_id: string; target: string; }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["PlanRequest"]; + }; + }; responses: { - /** @description Every current node's state at the state version node_status events continue from */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["NodeStatesRecord"]; + "application/json": components["schemas"]["MutationResponse"]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; }; }; /** @description Session rejected */ @@ -6111,16 +7368,14 @@ export interface operations { }; }; }; - readPersonNodeStatus: { + readPlan: { parameters: { - query: { - /** @description One exact published node key */ - node_key: string; - }; + query?: never; header?: never; path: { location_id: string; target: string; + request_id: string; }; cookie?: never; }; @@ -6131,15 +7386,8 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["NodeStatus"]; - }; - }; - /** @description Invalid node key */ - 400: { - headers: { - [name: string]: unknown; + "application/json": null | components["schemas"]["LocationWorkRecord"]; }; - content?: never; }; /** @description Session rejected */ 401: { @@ -6158,39 +7406,29 @@ export interface operations { }; }; }; - listPersonCatalogNodes: { + readPlanDiff: { parameters: { - query?: never; - header?: { - /** @description An ETag from an earlier response; 304 when the snapshot is unchanged */ - "If-None-Match"?: string | null; + query: { + /** @description The planned model whose diff to read */ + model: string; }; + header?: never; path: { location_id: string; target: string; + request_id: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Every node of the current snapshot without its state, which node-states serves; empty before the first publication */ 200: { headers: { - /** @description ""; absent before the first publication */ - ETag?: string; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["CatalogNodeRecord"][]; - }; - }; - /** @description Unchanged since the If-None-Match ETag */ - 304: { - headers: { - ETag?: string; - [name: string]: unknown; + "application/json": components["schemas"]["PlanDiffRead"]; }; - content?: never; }; /** @description Session rejected */ 401: { @@ -6207,33 +7445,43 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; + /** @description No diff of that model, or no view.sql on every current node */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; - listPersonNodeCosts: { + readPlanRows: { parameters: { - query?: { - /** @description Builds that started in the last this many days; defaults to 7, capped at 90 */ - days?: number; - /** @description Maximum builds; defaults to 100, capped at 1000 */ + query: { + /** @description The section to page */ + section: "full_refresh" | "query_changed" | "function_changed" | "config_changed" | "schema_changed" | "first_run" | "renamed" | "routine_models" | "migrations" | "column_migrations" | "table_type_conversions" | "retention" | "loader_reloads" | "loader_loads" | "source_reloads" | "source_loads" | "changed_functions" | "functions" | "first_run_seeds" | "changed_seeds" | "unchanged_seeds" | "python_nodes" | "held_back" | "unchanged" | "warnings"; + /** @description Rows to skip; 0 by default */ + offset?: number; + /** @description At most this many rows, capped at 1000 */ limit?: number; + /** @description Only rows whose name contains this, ignoring case */ + name?: string; }; header?: never; path: { location_id: string; target: string; - node_key: string; + request_id: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description The node's estimated query cost in each build, newest first */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["NodeCostRecord"][]; + "application/json": null | components["schemas"]["PlanRows"]; }; }; /** @description Session rejected */ @@ -6253,29 +7501,25 @@ export interface operations { }; }; }; - listPersonNodeRuns: { + readPlanSummary: { parameters: { - query?: { - /** @description Maximum recent runs; defaults to 100, capped at 1000 */ - limit?: number; - }; + query?: never; header?: never; path: { location_id: string; target: string; - node_key: string; + request_id: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Runs that built the node, newest first */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["NodeRunRecord"][]; + "application/json": null | components["schemas"]["PlanSummaryRead"]; }; }; /** @description Session rejected */ @@ -6295,25 +7539,25 @@ export interface operations { }; }; }; - readPersonNodeSql: { + readPersonProviders: { parameters: { query?: never; header?: never; path: { location_id: string; target: string; - node_key: string; }; cookie?: never; }; requestBody?: never; responses: { + /** @description Declared providers without setting values */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["NodeSql"]; + "application/json": components["schemas"]["ProvidersRead"]; }; }; /** @description Session rejected */ @@ -6333,9 +7577,12 @@ export interface operations { }; }; }; - requestPlan: { + requestRepublish: { parameters: { - query?: never; + query?: { + /** @description Seconds to wait for the new snapshot or the publish error, at most 60; 0 or absent returns at once */ + wait?: number; + }; header: { "x-sqb-csrf": string; }; @@ -6347,7 +7594,7 @@ export interface operations { }; requestBody: { content: { - "application/json": components["schemas"]["PlanRequest"]; + "application/json": components["schemas"]["PersonWorkRequest"]; }; }; responses: { @@ -6356,7 +7603,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["MutationResponse"]; + "application/json": components["schemas"]["RepublishStatus"]; }; }; 400: { @@ -6384,9 +7631,12 @@ export interface operations { }; }; }; - readPlan: { + readRepublish: { parameters: { - query?: never; + query?: { + /** @description Seconds to wait while the republish is pending, at most 60 */ + wait?: number; + }; header?: never; path: { location_id: string; @@ -6402,7 +7652,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["LocationWorkRecord"]; + "application/json": null | components["schemas"]["RepublishStatus"]; }; }; /** @description Session rejected */ @@ -6422,29 +7672,41 @@ export interface operations { }; }; }; - readPlanDiff: { + listPersonRuns: { parameters: { - query: { - /** @description The planned model whose diff to read */ - model: string; + query?: { + /** @description Page size; defaults to 100, capped at 1000 */ + limit?: number; + /** @description With before_run_id: continue after this run of the previous page */ + before_queued_at?: string; + before_run_id?: string; + /** @description List queued runs in claim order, each with its position and what it waits on */ + queued?: boolean; }; header?: never; path: { location_id: string; target: string; - request_id: string; }; cookie?: never; }; requestBody?: never; responses: { + /** @description Runs newest first, or the queue in claim order */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["PlanDiffRead"]; + "application/json": components["schemas"]["RunRecord"][]; + }; + }; + /** @description Only one of the before_* pair was given, or a cursor with queued */ + 400: { + headers: { + [name: string]: unknown; }; + content?: never; }; /** @description Session rejected */ 401: { @@ -6461,43 +7723,28 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; - /** @description No diff of that model, or no view.sql on every current node */ - 404: { - headers: { - [name: string]: unknown; - }; - content?: never; - }; }; }; - readPlanRows: { + readPersonRunCost: { parameters: { - query: { - /** @description The section to page */ - section: "full_refresh" | "query_changed" | "function_changed" | "config_changed" | "schema_changed" | "first_run" | "renamed" | "routine_models" | "migrations" | "column_migrations" | "table_type_conversions" | "retention" | "loader_reloads" | "loader_loads" | "source_reloads" | "source_loads" | "changed_functions" | "functions" | "first_run_seeds" | "changed_seeds" | "unchanged_seeds" | "python_nodes" | "held_back" | "unchanged" | "warnings"; - /** @description Rows to skip; 0 by default */ - offset?: number; - /** @description At most this many rows, capped at 1000 */ - limit?: number; - /** @description Only rows whose name contains this, ignoring case */ - name?: string; - }; + query?: never; header?: never; path: { location_id: string; target: string; - request_id: string; + run_id: string; }; cookie?: never; }; requestBody?: never; responses: { + /** @description The latest estimated query cost observation of the run and of each resource and warehouse it used; empty when none was synced */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["PlanRows"]; + "application/json": components["schemas"]["WarehouseResourceCostRecord"][]; }; }; /** @description Session rejected */ @@ -6515,27 +7762,40 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; + /** @description Run not found for a person who may view the whole target */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; - readPlanSummary: { + listPersonRunEvents: { parameters: { - query?: never; + query?: { + /** @description Return events after this storage cursor */ + after?: number; + /** @description Maximum events; defaults to 1000, capped at 5000 */ + limit?: number; + }; header?: never; path: { location_id: string; target: string; - request_id: string; + run_id: string; }; cookie?: never; }; requestBody?: never; responses: { + /** @description Event metadata oldest first, without payloads */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": null | components["schemas"]["PlanSummaryRead"]; + "application/json": components["schemas"]["RunEventRecord"][]; }; }; /** @description Session rejected */ @@ -6553,27 +7813,35 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; + /** @description Run not found for a person who may view the whole target */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; - readPersonProviders: { + listPersonRunIgnoredAudits: { parameters: { query?: never; header?: never; path: { location_id: string; target: string; + run_id: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Declared providers without setting values */ + /** @description The error-severity audit failures the run and its current group members let through, run by run */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ProvidersRead"]; + "application/json": components["schemas"]["RunIgnoredAuditFailure"][]; }; }; /** @description Session rejected */ @@ -6591,43 +7859,35 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; + /** @description Run not found for a person who may view the whole target */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; - listPersonRuns: { + listPersonRunNodes: { parameters: { - query?: { - /** @description Page size; defaults to 100, capped at 1000 */ - limit?: number; - /** @description With before_run_id: continue after this run of the previous page */ - before_queued_at?: string; - before_run_id?: string; - /** @description List queued runs in claim order, each with its position and what it waits on */ - queued?: boolean; - }; + query?: never; header?: never; path: { location_id: string; target: string; + run_id: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description Runs newest first, or the queue in claim order */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["RunRecord"][]; - }; - }; - /** @description Only one of the before_* pair was given, or a cursor with queued */ - 400: { - headers: { - [name: string]: unknown; + "application/json": components["schemas"]["RunNodeRecord"][]; }; - content?: never; }; /** @description Session rejected */ 401: { @@ -6644,9 +7904,16 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; + /** @description Run not found for a person who may view the whole target */ + 404: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; }; }; - readPersonRunCost: { + readPersonRunNodeError: { parameters: { query?: never; header?: never; @@ -6654,18 +7921,18 @@ export interface operations { location_id: string; target: string; run_id: string; + node_key: string; }; cookie?: never; }; requestBody?: never; responses: { - /** @description The latest estimated query cost observation of the run and of each resource and warehouse it used; empty when none was synced */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["WarehouseResourceCostRecord"][]; + "application/json": components["schemas"]["RunNodeFailure"]; }; }; /** @description Session rejected */ @@ -6675,6 +7942,7 @@ export interface operations { }; content?: never; }; + /** @description Needs view.evidence on the node */ 403: { headers: { [name: string]: unknown; @@ -6683,7 +7951,7 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; - /** @description Run not found for a person who may view the whole target */ + /** @description Node not found in this run */ 404: { headers: { [name: string]: unknown; @@ -6692,14 +7960,9 @@ export interface operations { }; }; }; - listPersonRunEvents: { + readPersonRunOutput: { parameters: { - query?: { - /** @description Return events after this storage cursor */ - after?: number; - /** @description Maximum events; defaults to 1000, capped at 5000 */ - limit?: number; - }; + query?: never; header?: never; path: { location_id: string; @@ -6710,13 +7973,12 @@ export interface operations { }; requestBody?: never; responses: { - /** @description Event metadata oldest first, without payloads */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["RunEventRecord"][]; + "application/json": components["schemas"]["RunOutput"]; }; }; /** @description Session rejected */ @@ -6726,6 +7988,7 @@ export interface operations { }; content?: never; }; + /** @description Needs view.evidence on every node the run selected */ 403: { headers: { [name: string]: unknown; @@ -6743,9 +8006,12 @@ export interface operations { }; }; }; - listPersonRunIgnoredAudits: { + downloadPersonRunOutput: { parameters: { - query?: never; + query: { + node: string; + stream?: components["schemas"]["OutputStream"]; + }; header?: never; path: { location_id: string; @@ -6756,13 +8022,13 @@ export interface operations { }; requestBody?: never; responses: { - /** @description The error-severity audit failures the run and its current group members let through, run by run */ + /** @description The node's whole stream */ 200: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["RunIgnoredAuditFailure"][]; + "text/plain": string; }; }; /** @description Session rejected */ @@ -6772,6 +8038,7 @@ export interface operations { }; content?: never; }; + /** @description Needs view.evidence on every node the run selected */ 403: { headers: { [name: string]: unknown; @@ -6787,11 +8054,22 @@ export interface operations { }; content?: never; }; + /** @description The server keeps no run output */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; }; }; - listPersonRunNodes: { + readPersonRunOutputIndex: { parameters: { - query?: never; + query?: { + node?: string; + }; header?: never; path: { location_id: string; @@ -6807,7 +8085,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["RunNodeRecord"][]; + "application/json": components["schemas"]["RunOutputIndex"]; }; }; /** @description Session rejected */ @@ -6817,6 +8095,7 @@ export interface operations { }; content?: never; }; + /** @description Needs view.evidence on every node the run selected */ 403: { headers: { [name: string]: unknown; @@ -6834,15 +8113,31 @@ export interface operations { }; }; }; - readPersonRunNodeError: { + readPersonRunOutputLines: { parameters: { - query?: never; + query?: { + /** @description The node key, or `run`; leave it out to read the whole run's output. */ + node?: string; + /** @description Only this stream's lines, keeping their numbers. */ + stream?: components["schemas"]["OutputStream"]; + /** @description Read forwards from this line, from 1. */ + from?: number; + /** @description Read the rows that end just before this line. */ + before?: number; + /** @description Read the last rows. */ + tail?: boolean; + /** @description How many rows to read, at most 2,000. */ + limit?: number; + /** @description Fold four or more lines that are the same but for their numbers into one row. */ + collapse?: boolean; + /** @description A line to keep open, with three lines either side, when folding. */ + around?: number; + }; header?: never; path: { location_id: string; target: string; run_id: string; - node_key: string; }; cookie?: never; }; @@ -6853,7 +8148,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["RunNodeFailure"]; + "application/json": components["schemas"]["OutputPage"]; }; }; /** @description Session rejected */ @@ -6863,7 +8158,7 @@ export interface operations { }; content?: never; }; - /** @description Needs view.evidence on the node */ + /** @description Needs view.evidence on every node the run selected */ 403: { headers: { [name: string]: unknown; @@ -6872,18 +8167,34 @@ export interface operations { "application/json": components["schemas"]["ApiErrorBody"]; }; }; - /** @description Node not found in this run */ + /** @description Run not found for a person who may view the whole target */ 404: { headers: { [name: string]: unknown; }; content?: never; }; + /** @description The server keeps no run output */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; }; }; - readPersonRunOutput: { + searchPersonRunOutput: { parameters: { - query?: never; + query: { + node: string; + stream?: components["schemas"]["OutputStream"]; + text: string; + /** @description Look from this line, which a forward search includes, as a backward one does. */ + from?: number; + direction?: "forward" | "backward"; + }; header?: never; path: { location_id: string; @@ -6899,7 +8210,16 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["RunOutput"]; + "application/json": components["schemas"]["OutputSearch"]; + }; + }; + /** @description Empty search text */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; }; }; /** @description Session rejected */ @@ -6925,6 +8245,15 @@ export interface operations { }; content?: never; }; + /** @description The server keeps no run output */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; }; }; listPersonRunStatements: { @@ -9048,6 +10377,62 @@ export interface operations { }; }; }; + output_batch: { + parameters: { + query?: never; + header?: never; + path: { + run_id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["OutputBatch"]; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OutputBatchReceipt"]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + /** @description Invalid credential */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Run not authorized */ + 403: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description The server keeps no run output */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; recall: { parameters: { query?: never; diff --git a/clients/typescript/tests/client.test.ts b/clients/typescript/tests/client.test.ts index 4c7c77a821..f2d4ce64c5 100644 --- a/clients/typescript/tests/client.test.ts +++ b/clients/typescript/tests/client.test.ts @@ -15,7 +15,7 @@ test("generated client preserves native scopes, replay, path encoding, SSE and b const env = { ...process.env }; delete env.SQLBUILD_CONTROL_DATABASE_URL; delete env.SQLBUILD_PLATFORM_WEBHOOK_URL; - const admin = (...args: string[]) => JSON.parse(execFileSync(executable, ["admin", ...args], { + const admin = (...args: string[]) => JSON.parse(execFileSync(executable, ["admin", ...args, "--json"], { cwd: directory, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], })); let baseUrl: string; diff --git a/compose.yml b/compose.yml index 9e80c298c6..d26d57fba1 100644 --- a/compose.yml +++ b/compose.yml @@ -32,6 +32,7 @@ services: group_add: ["${DOCKER_GID:?Set DOCKER_GID to the Docker socket group}"] volumes: - ${DOCKER_SOCKET:-/var/run/docker.sock}:/var/run/docker.sock + - output:/home/sqlbuild/.local/state/sqlbuild/output configs: - source: server target: /etc/sqlbuild/server.toml @@ -89,6 +90,7 @@ configs: volumes: control: + output: warehouse: networks: diff --git a/crates/sqlbuild-analysis/src/job_settings/constants.rs b/crates/sqlbuild-analysis/src/job_settings/constants.rs index 566e04e0f7..b2e5852418 100644 --- a/crates/sqlbuild-analysis/src/job_settings/constants.rs +++ b/crates/sqlbuild-analysis/src/job_settings/constants.rs @@ -14,7 +14,7 @@ pub const JOB_SETTING_CONFLICT_CODE: &str = "S027"; /// How a conflict names a job's `[retry]` table. pub const RETRY_SETTING: &str = "[retry]"; /// Every option of `sqb build`, in the parser's order, as a job setting. -pub const JOB_SETTINGS: [JobSettingSpec; 53] = [ +pub const JOB_SETTINGS: [JobSettingSpec; 54] = [ JobSettingSpec { name: "help", options: &["-h", "--help"], @@ -45,6 +45,16 @@ pub const JOB_SETTINGS: [JobSettingSpec; 53] = [ consumer: None, group: OneBuild, }, + JobSettingSpec { + name: "discover", + options: &["--discover"], + scope: RunRequest, + python_nodes: false, + whole_run: false, + command_line: CommandLineValues::OnlyTrue, + consumer: None, + group: OneBuild, + }, JobSettingSpec { name: "defer_to", options: &["--defer-to"], diff --git a/crates/sqlbuild-analysis/src/planner_selection/_helpers/unit_test_tokens.rs b/crates/sqlbuild-analysis/src/planner_selection/_helpers/unit_test_tokens.rs index b1c6182885..626472dfef 100644 --- a/crates/sqlbuild-analysis/src/planner_selection/_helpers/unit_test_tokens.rs +++ b/crates/sqlbuild-analysis/src/planner_selection/_helpers/unit_test_tokens.rs @@ -148,9 +148,18 @@ fn unknown(kind: &str, value: &str, names: &UnitTestSelectorNames) -> SelectorEr } } +/// The names `value` selects: itself, else every `value[]` of a `for_each` asset, else its glob matches. fn matching(value: &str, names: &BTreeSet) -> BTreeSet { + if names.contains(value) { + return BTreeSet::from([value.to_owned()]); + } if !is_pattern(value) { - return names.get(value).into_iter().cloned().collect(); + let prefix: String = format!("{value}["); + return names + .iter() + .filter(|name| name.starts_with(&prefix) && name.ends_with(']')) + .cloned() + .collect(); } names .iter() diff --git a/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs b/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs index 2bc9af1d3e..c63689fbe6 100644 --- a/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/planner_selection/tests/helpers.rs @@ -17,7 +17,7 @@ pub(super) fn name_set(values: &[&str]) -> BTreeSet { pub(super) fn selector_names() -> UnitTestSelectorNames { UnitTestSelectorNames { tests: name_set(&["test_customers", "test_orders"]), - resources: name_set(&["customers", "orders"]), + resources: name_set(&["customers", "orders", "step[a]", "step[b]"]), } } diff --git a/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs b/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs index e93a0bc9f7..67acc8357c 100644 --- a/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs +++ b/crates/sqlbuild-analysis/src/planner_selection/tests/test_planner_selection.rs @@ -33,6 +33,20 @@ fn given_selector_groups_when_splitting_unit_tests_then_moves_or_rejects_them() accepts_unit_tests: false, expected_split: Ok(split(&["orders"], &[], true)), }, + UnitTestSplitTestCase { + description: "a discovered node's bracketed name is that resource, not a pattern", + select: texts(&["step[b]"]), + exclude: Vec::new(), + accepts_unit_tests: true, + expected_split: Ok(split(&["step[b]"], &[], true)), + }, + UnitTestSplitTestCase { + description: "a for_each asset's name is a resource", + select: texts(&["step"]), + exclude: Vec::new(), + accepts_unit_tests: true, + expected_split: Ok(split(&["step"], &[], true)), + }, UnitTestSplitTestCase { description: "commands without unit tests reject them", select: texts(&["test_orders"]), diff --git a/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs b/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs index 9cc6c33175..8f29b2369c 100644 --- a/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs +++ b/crates/sqlbuild-analysis/src/python_selection/_helpers/nodes.rs @@ -93,6 +93,24 @@ impl<'graph> NodeIndex<'graph> { self.by_name.get(name).copied() } + /// The node named exactly `value`, or else every node `value[]` of a `for_each` asset. + pub(crate) fn named(&self, value: &str) -> Vec<&'graph PythonSelectionNode> { + if let Some(node) = self.node(value) { + return vec![node]; + } + let prefix: String = format!("{value}["); + self.by_name + .iter() + .filter(|(name, _)| name.starts_with(&prefix) && name.ends_with(']')) + .map(|(_, node)| *node) + .collect() + } + + /// Whether `value` is read as a pattern: it uses a glob character and names no node exactly. + pub(crate) fn is_pattern(&self, value: &str) -> bool { + is_pattern(value) && self.node(value).is_none() + } + pub(crate) fn edges(&self, name: &str, direction: EdgeDirection) -> &'graph [String] { let edges: &HashMap<&'graph str, &'graph [String]> = match direction { EdgeDirection::Upstream => &self.upstream, @@ -264,11 +282,11 @@ fn under_path(index: &NodeIndex<'_>, value: &str) -> Resolved { fn lookup(index: &NodeIndex<'_>, kind: &str, value: &str) -> Resolved { if kind == NAME_KIND { - if !is_pattern(value) { + if !index.is_pattern(value) { return Ok(index - .node(value) - .map(|node| node.name.clone()) + .named(value) .into_iter() + .map(|node| node.name.clone()) .collect()); } return Ok(index @@ -284,15 +302,12 @@ fn lookup(index: &NodeIndex<'_>, kind: &str, value: &str) -> Resolved { format!("selector type '{kind}' does not map to a Python node type"), )); } - if !is_pattern(value) { + if !index.is_pattern(value) { return Ok(index - .graph - .nodes - .iter() - .rev() - .find(|node| node.kind == kind && node.name == value) - .map(|node| node.name.clone()) + .named(value) .into_iter() + .filter(|node| node.kind == kind) + .map(|node| node.name.clone()) .collect()); } Ok(index diff --git a/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs b/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs index a7e67676ae..276b0c240d 100644 --- a/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs +++ b/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs @@ -15,7 +15,7 @@ use crate::graph::main::parse_selector::parse_selector; use crate::graph::main::resolve_selectors::resolve_selectors; use crate::graph::models::{BuildResources, EdgeDirection, ParsedSelector}; use crate::python_selection::_helpers::nodes::{ - Names, error, folder_root, is_pattern, select_nodes, selector_folder, unit_test_error, + Names, error, folder_root, select_nodes, selector_folder, unit_test_error, }; use crate::python_selection::_helpers::validation::{ source_loaders, terminal_loaders, validate_boundaries, validate_selected_dependencies, @@ -506,9 +506,9 @@ fn unknown_name(value: &str) -> SelectorError { fn resolve_name(context: &SelectionContext<'_>, raw: &str, value: &str) -> Resolved { let terminal: HashMap<&str, &str> = terminal_loaders(context.sql); - if !is_pattern(value) { + if !context.nodes.is_pattern(value) { let sql: bool = context.sql_names.contains_key(value); - let python: bool = context.nodes.node(value).is_some(); + let python: bool = !context.nodes.named(value).is_empty(); return match (sql, python) { (true, _) if terminal.contains_key(value) => resolve_sql(context, raw), (true, true) => Err(both_error(value)), diff --git a/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs b/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs index 64ae70e8e5..6ace228bd1 100644 --- a/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/python_selection/tests/helpers.rs @@ -90,9 +90,30 @@ fn failure(error: SelectorError) -> OwnedFailure { (error.code.to_owned(), error.message) } -/// The inventory rows of the orders Python nodes. -fn inventory_nodes() -> Vec { - ORDERS_NODES +/// The orders nodes plus `step`, a `for_each` asset with items `a` and `b`, and `step_total`. +const DISCOVERED_NODES: &[NodeSpec] = &[ + ("step[a]", "asset", "python/plan/node.py", &[], &[], &[]), + ( + "step[b]", + "asset", + "python/plan/node.py", + &[], + &["step[a]"], + &[], + ), + ( + "step_total", + "asset", + "python/plan/total.py", + &[], + &["step[b]"], + &[], + ), +]; + +/// The inventory rows of `nodes`. +fn inventory_nodes(nodes: &[NodeSpec]) -> Vec { + nodes .iter() .map(|(name, _, path, tags, upstream, _)| InventoryNode { name: (*name).to_owned(), @@ -105,9 +126,19 @@ fn inventory_nodes() -> Vec { /// The orders Python node graph, indexed by the native inventory. pub(super) fn orders_python_graph() -> PythonSelectionGraph { - let indexes: InventoryIndexes = python_node_graph_indexes(&inventory_nodes()); + python_graph(ORDERS_NODES) +} + +/// The orders Python node graph with the discovered nodes of `step` and a node after them. +pub(super) fn discovered_python_graph() -> PythonSelectionGraph { + python_graph(&[ORDERS_NODES, DISCOVERED_NODES].concat()) +} + +/// The Python node graph of `nodes`, indexed by the native inventory. +fn python_graph(nodes: &[NodeSpec]) -> PythonSelectionGraph { + let indexes: InventoryIndexes = python_node_graph_indexes(&inventory_nodes(nodes)); PythonSelectionGraph { - nodes: ORDERS_NODES + nodes: nodes .iter() .map(|(name, kind, _, _, _, sql_deps)| PythonSelectionNode { name: (*name).to_owned(), diff --git a/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs b/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs index 26e26be759..97109c375e 100644 --- a/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs +++ b/crates/sqlbuild-analysis/src/python_selection/tests/test_python_selection.rs @@ -1,6 +1,6 @@ use crate::python_selection::tests::helpers::{ - excluded_names, expected_names, expected_run, indexed_folder, node_names, - published_orders_graph, run, run_over, + discovered_python_graph, excluded_names, expected_names, expected_run, indexed_folder, + node_names, published_orders_graph, run, run_over, }; use crate::python_selection::tests::test_types::{ InventoryTestCase, NodeSelectorTestCase, RunSelectionTestCase, @@ -319,3 +319,51 @@ fn given_check_exclude_tokens_when_resolving_then_unmatched_tokens_are_skipped() ); } } + +#[test] +fn given_discovered_nodes_when_selecting_then_an_exact_name_is_one_node_and_the_asset_is_all() { + let test_cases = [ + RunSelectionTestCase { + description: "a bracketed name is that node, not a glob", + select: &["step[a]"], + exclude: &[], + expected_selection: Ok((&[], &["step[a]"])), + }, + RunSelectionTestCase { + description: "a bracketed name with downstream", + select: &["step[b]+"], + exclude: &[], + expected_selection: Ok((&[], &["step[b]", "step_total"])), + }, + RunSelectionTestCase { + description: "the asset selects every node of its family", + select: &["asset:step"], + exclude: &[], + expected_selection: Ok((&[], &["step[a]", "step[b]"])), + }, + RunSelectionTestCase { + description: "the bare asset name selects the family too", + select: &["step"], + exclude: &["step[a]"], + expected_selection: Ok((&[], &["step[b]"])), + }, + RunSelectionTestCase { + description: "a glob still matches across names", + select: &["step*"], + exclude: &[], + expected_selection: Ok((&[], &["step[a]", "step[b]", "step_total"])), + }, + ]; + let graph = discovered_python_graph(); + + for test_case in test_cases { + let selection = run_over(&graph, test_case.select, test_case.exclude); + + assert_eq!( + selection, + expected_run(test_case.expected_selection), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-analysis/src/sql_macros/_helpers/parsing/body.rs b/crates/sqlbuild-analysis/src/sql_macros/_helpers/parsing/body.rs index 155c2939bb..19a8c88587 100644 --- a/crates/sqlbuild-analysis/src/sql_macros/_helpers/parsing/body.rs +++ b/crates/sqlbuild-analysis/src/sql_macros/_helpers/parsing/body.rs @@ -8,6 +8,9 @@ use sqlquack_syntax::{Expression, ExpressionWalk, Parsed}; use crate::analysis_route::main::analysis_route::analysis_route; use crate::analysis_route::models::AnalysisRoute; use crate::analysis_route::types::NativeDialect; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; +use sqlbuild_sqltext::sql_scan::main::expansion_followed_by::expansion_followed_by; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; use crate::sql_macros::_helpers::parsing::captures::{output_selects, slot_captures}; use crate::sql_macros::_helpers::parsing::header::unquoted; @@ -20,6 +23,7 @@ use crate::sql_macros::_helpers::parsing::parameters::{ use crate::sql_macros::_helpers::parsing::slots::{SlotRead, check_group_positions, slot_reads}; use crate::sql_macros::_helpers::rendering::arguments::is_atomic; use crate::sql_macros::_helpers::typing::typed_calls::{shifted, spliced}; +use crate::sql_macros::constants::PARAMETER_CLOSINGS; use crate::sql_macros::constants::{ ARGUMENT_CODE, INVALID_DEFINITION_CODE, NAME_CLASH_CODE, SLOT_PLACEHOLDER_PREFIX, }; @@ -308,7 +312,7 @@ fn substituted( kind: &ParameterKind, parameter: &str, argument: &RenderedArgument, - (sql, scanned, token): (&str, &[Token], usize), + ((sql, scanned, token), syntax): ((&str, &[Token], usize), Option<&LexicalSyntax>), ) -> String { match kind { ParameterKind::Relation { .. } => { @@ -329,7 +333,7 @@ fn substituted( | ParameterKind::Constant { .. } if !is_atomic(&argument.sql) => { - format!("({})", argument.sql) + format!("({})", expansion_followed_by(&argument.sql, ")", syntax)) } _ => argument.sql.clone(), } @@ -643,7 +647,7 @@ fn check_forwarded_kinds( /// `body` with each `@name` replaced by its argument, token by token, and the calls it holds. fn substituted_body( (definition, outer): (&SqlMacroDefinition, Option<&SqlMacroDefinition>), - (body, scanned): (&str, &[Token]), + (body, scanned, syntax): (&str, &[Token], Option<&LexicalSyntax>), (references, reads): (&[ParameterReference], &[SlotRead]), (arguments, body_calls): (&[RenderedArgument], &[TypedCall]), ) -> (String, Vec) { @@ -651,6 +655,7 @@ fn substituted_body( let mut splices: Vec = Vec::new(); let mut argument_calls: Vec = Vec::new(); let mut cursor: usize = 0; + let mut replacements: Vec<((usize, usize), String, &RenderedArgument)> = Vec::new(); for (position, reference) in references.iter().enumerate() { let Some(argument) = arguments.iter().find(|argument| { definition.parameters[argument.parameter] @@ -664,12 +669,11 @@ fn substituted_body( let source: (usize, usize) = read.map_or((reference.start, reference.end), |read| { (read.start, read.end) }); - expanded.push_str(&body[cursor..source.0]); let text: String = substituted( ¶meter.kind, ¶meter.name, argument, - (body, scanned, reference.token), + ((body, scanned, reference.token), syntax), ); let text: String = match read { Some(read) => substituted_read( @@ -680,17 +684,39 @@ fn substituted_body( ), None => text, }; + replacements.push((source, text, argument)); + } + let sites: Vec<(usize, usize, &str)> = replacements + .iter() + .map(|((start, end), text, _)| (*start, *end, text.as_str())) + .collect(); + let mut bounded = bounded_expansions(body, &sites, syntax) + .into_iter() + .peekable(); + for (index, (source, original, argument)) in replacements.iter().enumerate() { + let (text, lead): (String, usize) = bounded + .next_if(|expansion| expansion.index == index) + .map_or_else( + || (original.clone(), 0), + |expansion| (expansion.text, expansion.lead), + ); + let source: (usize, usize) = *source; + expanded.push_str(&body[cursor..source.0]); let start: usize = expanded.len(); if !argument.calls.is_empty() { - let inner: Option = if text == argument.sql { + let inner: Option = if *original == argument.sql { Some(0) - } else if text.len() == argument.sql.len() + 2 && text[1..].starts_with(&argument.sql) { + } else if original + .strip_prefix('(') + .and_then(|rest| rest.strip_prefix(argument.sql.as_str())) + .is_some_and(|rest| PARAMETER_CLOSINGS.contains(&rest)) + { Some(1) } else { None }; if let Some(inner) = inner { - argument_calls.extend(shifted(argument.calls.clone(), start + inner)); + argument_calls.extend(shifted(argument.calls.clone(), start + lead + inner)); } } expanded.push_str(&text); @@ -723,7 +749,7 @@ fn within(calls: Vec, (start, end): (usize, usize)) -> Vec pub(crate) fn expand_body( parser: &dyn NativeDialect, (definition, outer): (&SqlMacroDefinition, Option<&SqlMacroDefinition>), - body: &ExpandedText, + (body, syntax): (&ExpandedText, Option<&LexicalSyntax>), arguments: &[RenderedArgument], ) -> Result { let (body, body_calls): (&str, &[TypedCall]) = (&body.sql, &body.calls); @@ -762,7 +788,7 @@ pub(crate) fn expand_body( check_forwarded_kinds(definition, arguments, outer)?; let (expanded, calls) = substituted_body( (definition, outer), - (body, &scanned), + (body, &scanned, syntax), (&references, &reads), (arguments, body_calls), ); diff --git a/crates/sqlbuild-analysis/src/sql_macros/_helpers/rendering/expansion.rs b/crates/sqlbuild-analysis/src/sql_macros/_helpers/rendering/expansion.rs index 2a6915c771..cfb8faa3fc 100644 --- a/crates/sqlbuild-analysis/src/sql_macros/_helpers/rendering/expansion.rs +++ b/crates/sqlbuild-analysis/src/sql_macros/_helpers/rendering/expansion.rs @@ -34,6 +34,8 @@ use crate::sql_macros::models::{ SqlMacroForm, SqlMacroLocation, TextContext, TypedCall, }; use crate::sql_macros::types::{ConstantShape, SqlMacroHost, SqlMacroScope}; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; +use sqlbuild_sqltext::sql_scan::main::expansion_followed_by::expansion_followed_by; use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; /// The outer SQL macro calls of `text`, or why its `@` constructs could not be read. @@ -153,9 +155,26 @@ pub(crate) fn expand_text( let mut spliced_text: String = String::with_capacity(context.text.len()); let mut typed: Vec = Vec::new(); let mut cursor: usize = 0; + let mut expansions: Vec = Vec::with_capacity(calls.len()); for call in &calls { let (expansion, updated) = expand_call(host, context, (&scanned, inserted), call)?; inserted = updated; + expansions.push(expansion); + } + let sites: Vec<(usize, usize, &str)> = calls + .iter() + .zip(&expansions) + .map(|(call, expansion)| (call.start, call.replaced_end, expansion.sql.as_str())) + .collect(); + for bounded in bounded_expansions(context.text, &sites, syntax) { + let expansion: &mut ExpandedText = &mut expansions[bounded.index]; + expansion.sql = bounded.text; + for call in &mut expansion.calls { + call.start += bounded.lead; + call.end += bounded.lead; + } + } + for (call, expansion) in calls.iter().zip(expansions) { spliced_text.push_str(&context.text[cursor..call.start]); typed.extend(shifted(expansion.calls, spliced_text.len())); spliced_text.push_str(&expansion.sql); @@ -265,8 +284,13 @@ pub(crate) fn expand_call( SqlMacroScope::Macro(outer) => Some(outer.as_ref()), SqlMacroScope::Caller => None, }; - let mut expansion: BodyExpansion = expand_body(parser, (&definition, outer), &body, &rendered) - .map_err(|error| error.at(body_location(&definition)))?; + let mut expansion: BodyExpansion = expand_body( + parser, + (&definition, outer), + (&body, host.lexical_syntax()), + &rendered, + ) + .map_err(|error| error.at(body_location(&definition)))?; expansion.like = definition.returns_like.as_deref().and_then(|name| { rendered .iter() @@ -328,7 +352,7 @@ pub(crate) fn expand_call( placed( &definition, (&site, inserted, line_continues), - &expansion, + (&expansion, host.lexical_syntax()), context.owner, ) .map_err(ExpansionFailure::Macro) @@ -444,13 +468,13 @@ fn python_string(sql: &str) -> String { fn placed( definition: &SqlMacroDefinition, (site, inserted, line_continues): (&CallSite<'_>, InsertedNames, bool), - expansion: &BodyExpansion, + (expansion, syntax): (&BodyExpansion, Option<&LexicalSyntax>), owner: &str, ) -> Result<(ExpandedText, InsertedNames), SqlMacroError> { let (text, inserted, prefix) = placed_text( definition, (site, inserted, line_continues), - expansion, + (expansion, syntax), owner, )?; let mut calls: Vec = shifted(expansion.calls.clone(), prefix).collect(); @@ -471,7 +495,7 @@ fn placed( fn placed_text( definition: &SqlMacroDefinition, (site, inserted, line_continues): (&CallSite<'_>, InsertedNames, bool), - expansion: &BodyExpansion, + (expansion, syntax): (&BodyExpansion, Option<&LexicalSyntax>), owner: &str, ) -> Result<(String, InsertedNames, usize), SqlMacroError> { let closed = |after: &str| { @@ -479,7 +503,11 @@ fn placed_text( None => line_continues, Some(next) => next != '\n' && next != '\r', }; - with_line_comment_closed(&expansion.sql, followed) + expansion_followed_by( + &with_line_comment_closed(&expansion.sql, followed), + after, + syntax, + ) }; let position: CallPosition = site.position(); let name: &str = &definition.name; diff --git a/crates/sqlbuild-analysis/src/sql_macros/_helpers/typing/returns_check.rs b/crates/sqlbuild-analysis/src/sql_macros/_helpers/typing/returns_check.rs index e0d8e6ef93..9a1809843c 100644 --- a/crates/sqlbuild-analysis/src/sql_macros/_helpers/typing/returns_check.rs +++ b/crates/sqlbuild-analysis/src/sql_macros/_helpers/typing/returns_check.rs @@ -91,7 +91,7 @@ fn body_probe( slots: Vec::new(), }); } - let expansion = match expand_body(parser, (definition, None), body, &arguments) { + let expansion = match expand_body(parser, (definition, None), (body, None), &arguments) { Ok(expansion) => expansion, Err(_) => return None, }; diff --git a/crates/sqlbuild-analysis/src/sql_macros/constants.rs b/crates/sqlbuild-analysis/src/sql_macros/constants.rs index 29e6b8dd67..be95f5c55e 100644 --- a/crates/sqlbuild-analysis/src/sql_macros/constants.rs +++ b/crates/sqlbuild-analysis/src/sql_macros/constants.rs @@ -147,3 +147,6 @@ pub(crate) const BIGQUERY_BIG_DECIMAL_NAMES: [&str; 2] = ["BIGNUMERIC", "BIGDECI pub(crate) const RELATION_FUNCTION_PREFIX: &str = "__"; /// Parse-verified marker sets a process keeps before starting over; each holds one model's SQL. pub(crate) const MARKER_MEMO_ENTRIES: usize = 8192; + +/// What closes a parenthesised argument, after its last line comment when it has one. +pub(crate) const PARAMETER_CLOSINGS: [&str; 2] = [")", "\n)"]; diff --git a/crates/sqlbuild-attachments/src/audits/_helpers/parameters.rs b/crates/sqlbuild-attachments/src/audits/_helpers/parameters.rs index 7392a5dcbc..cc77dd24bb 100644 --- a/crates/sqlbuild-attachments/src/audits/_helpers/parameters.rs +++ b/crates/sqlbuild-attachments/src/audits/_helpers/parameters.rs @@ -1,6 +1,8 @@ //! Python's raw and quoted SQL argument patterns and argument value rendering. use crate::audits::models::ArgumentValue; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; /// One `@name` or `@'name'` occurrence, in byte offsets. pub(crate) struct ParameterMatch<'sql> { @@ -123,10 +125,12 @@ pub(crate) enum RenderStop { pub(crate) fn render_parameterized_sql( sql: &str, arguments: &[(String, ArgumentValue)], + syntax: Option<&LexicalSyntax>, ) -> Result { let matches = parameter_matches(sql); let mut rendered: String = String::with_capacity(sql.len()); let mut previous_end: usize = 0; + let mut texts: Vec = Vec::with_capacity(matches.len()); for item in &matches { let Some((_, value)) = arguments .iter() @@ -134,11 +138,22 @@ pub(crate) fn render_parameterized_sql( else { return Err(RenderStop::MissingArgument(item.name.to_owned())); }; - rendered.push_str(&sql[previous_end..item.start]); let Some(text) = render_value(value, item.quoted) else { return Err(RenderStop::UnsupportedValue(item.name.to_owned())); }; - rendered.push_str(&text); + texts.push(text); + } + let sites: Vec<(usize, usize, &str)> = matches + .iter() + .zip(&texts) + .map(|(item, text)| (item.start, item.end, text.as_str())) + .collect(); + for bounded in bounded_expansions(sql, &sites, syntax) { + texts[bounded.index] = bounded.text; + } + for (item, text) in matches.iter().zip(&texts) { + rendered.push_str(&sql[previous_end..item.start]); + rendered.push_str(text); previous_end = item.end; } rendered.push_str(&sql[previous_end..]); diff --git a/crates/sqlbuild-attachments/src/audits/_helpers/rendering.rs b/crates/sqlbuild-attachments/src/audits/_helpers/rendering.rs index 228febd8cc..5e916eb860 100644 --- a/crates/sqlbuild-attachments/src/audits/_helpers/rendering.rs +++ b/crates/sqlbuild-attachments/src/audits/_helpers/rendering.rs @@ -9,6 +9,7 @@ use crate::audits::constants::{ SEED_RESOURCE, SOURCE_RESOURCE, }; use crate::audits::models::{ArgumentValue, AuditAttachment, PolicySource}; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; /// Severity first, then run scope, as Python resolves them after expanding the SQL. pub(crate) fn policies( @@ -42,8 +43,9 @@ pub(crate) fn rendered( attachment: &AuditAttachment, sql: &str, arguments: &[(String, ArgumentValue)], + syntax: Option<&LexicalSyntax>, ) -> Result { - render_parameterized_sql(sql, arguments).map_err(|stop| match stop { + render_parameterized_sql(sql, arguments, syntax).map_err(|stop| match stop { RenderStop::MissingArgument(name) => format!( "{} is missing argument '{name}' for generic audit '{}'{}", attachment.owner_label, diff --git a/crates/sqlbuild-attachments/src/audits/main/render_attached_audit.rs b/crates/sqlbuild-attachments/src/audits/main/render_attached_audit.rs index 885e4d9b4b..0878f832b3 100644 --- a/crates/sqlbuild-attachments/src/audits/main/render_attached_audit.rs +++ b/crates/sqlbuild-attachments/src/audits/main/render_attached_audit.rs @@ -4,17 +4,21 @@ use crate::audits::_helpers::rendering::{ merged_arguments, policies, rendered, unreferenced_relationship_target, unused_argument, }; use crate::audits::models::{ArgumentValue, AuditAttachment, AuditRendering, RenderedAudit}; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; -/// Render one attachment, or the error rendering raises. +/// Render one attachment in `syntax`, or the error rendering raises. #[must_use] -pub fn render_attached_audit(attachment: &AuditAttachment) -> AuditRendering { +pub fn render_attached_audit( + attachment: &AuditAttachment, + syntax: Option<&LexicalSyntax>, +) -> AuditRendering { let rendering = || -> Result { let arguments: Vec<(String, ArgumentValue)> = merged_arguments(attachment)?; - let sql_body: String = rendered(attachment, &attachment.sql_body, &arguments)?; + let sql_body: String = rendered(attachment, &attachment.sql_body, &arguments, syntax)?; let evidence_sql: Option = attachment .evidence_sql .as_deref() - .map(|evidence| rendered(attachment, evidence, &arguments)) + .map(|evidence| rendered(attachment, evidence, &arguments, syntax)) .transpose()?; if let Some(message) = unused_argument(attachment).or_else(|| unreferenced_relationship_target(attachment)) diff --git a/crates/sqlbuild-attachments/src/audits/main/render_parameterized_sql.rs b/crates/sqlbuild-attachments/src/audits/main/render_parameterized_sql.rs index f26cc18c19..7f68516a38 100644 --- a/crates/sqlbuild-attachments/src/audits/main/render_parameterized_sql.rs +++ b/crates/sqlbuild-attachments/src/audits/main/render_parameterized_sql.rs @@ -1,11 +1,12 @@ use crate::audits::_helpers::parameters::{RenderStop, parameter_matches}; use crate::audits::models::{ArgumentValue, ParameterRenderStop}; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; /// `render_parameterized_sql`: raw and quoted arguments rendered into reusable SQL text. pub fn render_parameterized_sql( sql: &str, arguments: &[(String, ArgumentValue)], - reject_unused: bool, + (reject_unused, syntax): (bool, Option<&LexicalSyntax>), ) -> Result { if reject_unused { let referenced: Vec<&str> = parameter_matches(sql) @@ -23,10 +24,10 @@ pub fn render_parameterized_sql( return Err(ParameterRenderStop::UnusedArguments(unused)); } } - crate::audits::_helpers::parameters::render_parameterized_sql(sql, arguments).map_err(|stop| { - match stop { + crate::audits::_helpers::parameters::render_parameterized_sql(sql, arguments, syntax).map_err( + |stop| match stop { RenderStop::MissingArgument(name) => ParameterRenderStop::MissingArgument(name), RenderStop::UnsupportedValue(name) => ParameterRenderStop::UnsupportedValue(name), - } - }) + }, + ) } diff --git a/crates/sqlbuild-attachments/src/audits/tests/helpers.rs b/crates/sqlbuild-attachments/src/audits/tests/helpers.rs index 245ce1628d..6c10347805 100644 --- a/crates/sqlbuild-attachments/src/audits/tests/helpers.rs +++ b/crates/sqlbuild-attachments/src/audits/tests/helpers.rs @@ -28,7 +28,7 @@ pub(super) fn order_arguments() -> Vec<(String, ArgumentValue)> { } pub(super) fn rendered_sql(sql: &str) -> Result { - render_parameterized_sql(sql, &order_arguments()) + render_parameterized_sql(sql, &order_arguments(), None) } /// A violations audit over `@column` with the given explicit arguments and policies. diff --git a/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs b/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs index b639d058d8..8fc33cf95a 100644 --- a/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs +++ b/crates/sqlbuild-attachments/src/audits/tests/test_render_attached_audit.rs @@ -220,7 +220,7 @@ fn given_attached_audits_when_rendering_then_python_rendering_is_returned() { for test_case in test_cases { assert_eq!( - render_attached_audit(&test_case.attachment), + render_attached_audit(&test_case.attachment, None), test_case.expected_rendering, "{}", test_case.description diff --git a/crates/sqlbuild-attachments/src/audits/tests/test_render_parameterized_sql.rs b/crates/sqlbuild-attachments/src/audits/tests/test_render_parameterized_sql.rs index 963f99bc5f..28dcec223c 100644 --- a/crates/sqlbuild-attachments/src/audits/tests/test_render_parameterized_sql.rs +++ b/crates/sqlbuild-attachments/src/audits/tests/test_render_parameterized_sql.rs @@ -78,7 +78,7 @@ fn given_unreferenced_arguments_when_rejecting_unused_then_their_sorted_names_st }) .collect(); assert_eq!( - render_parameterized_sql(test_case.sql, &arguments, true), + render_parameterized_sql(test_case.sql, &arguments, (true, None)), test_case.expected_sql.map(str::to_owned), "{}", test_case.description diff --git a/crates/sqlbuild-attachments/src/cursor_intrinsics/_helpers/replacement.rs b/crates/sqlbuild-attachments/src/cursor_intrinsics/_helpers/replacement.rs index ba51a73d01..c31b7579ce 100644 --- a/crates/sqlbuild-attachments/src/cursor_intrinsics/_helpers/replacement.rs +++ b/crates/sqlbuild-attachments/src/cursor_intrinsics/_helpers/replacement.rs @@ -5,8 +5,9 @@ use crate::cursor_intrinsics::_helpers::scan::{ }; use crate::cursor_intrinsics::models::IntrinsicSpan; use crate::sql_lexing::main::unclosed_message::unclosed_message; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; -/// `sql` with each cursor intrinsic call replaced and each call's byte span, or the call's error. +/// `sql` with each cursor intrinsic call replaced and each call's byte span, or the call's error; a bound is a number or quoted literal, so only `--`, which every dialect has, can form beside one. pub(crate) fn replaced_with_spans( sql: &str, context: &str, @@ -19,6 +20,7 @@ pub(crate) fn replaced_with_spans( let mut last: usize = 0; let mut spans: Vec = Vec::new(); let mut index: usize = 0; + let mut texts: Vec = Vec::new(); while index < sql.len() { let (name, end): (&str, usize) = match step(sql, index) { ScanStep::Next(next) => { @@ -45,18 +47,30 @@ pub(crate) fn replaced_with_spans( )); } }; - replaced.push_str(&sql[last..index]); - let output_start: usize = replaced.len(); - replaced.push_str(&replacement(name)); + texts.push(replacement(name)); spans.push(IntrinsicSpan { source_start: index, source_end: close + 1, - output_start, - output_end: replaced.len(), + output_start: 0, + output_end: 0, }); - last = close + 1; index = close + 1; } + let sites: Vec<(usize, usize, &str)> = spans + .iter() + .zip(&texts) + .map(|(span, text)| (span.source_start, span.source_end, text.as_str())) + .collect(); + for bounded in bounded_expansions(sql, &sites, None) { + texts[bounded.index] = bounded.text; + } + for (span, text) in spans.iter_mut().zip(&texts) { + replaced.push_str(&sql[last..span.source_start]); + span.output_start = replaced.len(); + replaced.push_str(text); + span.output_end = replaced.len(); + last = span.source_end; + } replaced.push_str(&sql[last..]); Ok((replaced, spans)) } diff --git a/crates/sqlbuild-cli/src/adhoc/constants.rs b/crates/sqlbuild-cli/src/adhoc/constants.rs index 58a4cb4afc..a6a1c93e79 100644 --- a/crates/sqlbuild-cli/src/adhoc/constants.rs +++ b/crates/sqlbuild-cli/src/adhoc/constants.rs @@ -98,7 +98,7 @@ pub(crate) const INTEGER_CONVERTERS: [&str; 2] = ["int", POSITIVE_INTEGER_CONVER pub(crate) const POSITIVE_INTEGER_CONVERTER: &str = "_positive_integer"; /// Refused destinations: the flag people typed and why an ad-hoc run cannot honour it. -pub(crate) const REFUSED_DESTS: [(&str, &str, &str); 23] = [ +pub(crate) const REFUSED_DESTS: [(&str, &str, &str); 24] = [ ( "select_file", "--select-file", @@ -126,6 +126,11 @@ pub(crate) const REFUSED_DESTS: [(&str, &str, &str); 23] = [ "workers always verify the published SQL", ), ("no_cache", "--no-cache", "workers manage their own cache"), + ( + "discover", + "--discover", + "workers run the discovered sets the snapshot saved", + ), ( "target", "--target", diff --git a/crates/sqlbuild-cli/src/argv/command_table.json b/crates/sqlbuild-cli/src/argv/command_table.json index f509e7e865..6c08e7760f 100644 --- a/crates/sqlbuild-cli/src/argv/command_table.json +++ b/crates/sqlbuild-cli/src/argv/command_table.json @@ -151,13 +151,15 @@ "name": "dev", "parser": { "prog": "sqb dev", - "description": "Run the local control API, scheduler and reloadable code location. Authentication is disabled only on loopback; triggers start paused. The web UI is served at the same address.", + "description": "Run the local control API, scheduler and reloadable code location. There is no sign-in, so it listens on loopback and takes only local names unless --host or --allow-host opens it up; triggers start paused. The web UI is served at the same address.", "groups": [{"title": "positional arguments"}, {"title": "options"}], "actions": [ {"kind": "help", "options": ["-h", "--help"], "dest": "help", "nargs": 0, "default": {"suppress": true}, "help": "show this help message and exit", "group": 1}, {"kind": "store", "options": ["--project-dir", "--sqb-project-dir"], "dest": "project_dir", "default": {"suppress": true}, "help": "SQLBuild project directory", "group": 1}, {"kind": "store", "options": ["--target"], "dest": "target", "help": "target to compile and run (default: configured target)", "group": 1}, - {"kind": "store", "options": ["--port"], "dest": "control_port", "default": 8000, "type": "int", "help": "loopback TCP port, or 0 to choose a free port (default: 8000)", "group": 1}, + {"kind": "store", "options": ["--port"], "dest": "control_port", "default": 8000, "type": "int", "help": "TCP port, or 0 to choose a free port (default: 8000)", "group": 1}, + {"kind": "store", "options": ["--host"], "dest": "control_host", "metavar": "ADDRESS", "help": "IP address to listen on (default: 127.0.0.1); beyond loopback, anyone who can reach it has full access without signing in, with your credentials", "group": 1}, + {"kind": "append", "options": ["--allow-host"], "dest": "development_allow_host", "default": [], "metavar": "NAME", "help": "also accept this name or IP address, optionally with :port, in Host and Origin (repeatable); anyone who can reach it has full access without signing in, with your credentials", "group": 1}, {"kind": "store", "options": ["--control-store-url"], "dest": "development_store_url", "help": "control store URL or path (default: .sqlbuild/control.sqlite3 in the project)", "group": 1}, {"kind": "store_true", "options": ["--no-scheduler"], "dest": "control_no_scheduler", "nargs": 0, "const": true, "default": false, "help": "serve and reload without executing scheduled work", "group": 1}, {"kind": "store_true", "options": ["--triggers"], "dest": "development_triggers", "nargs": 0, "const": true, "default": false, "help": "preserve trigger defaults and operator overrides instead of pausing on startup", "group": 1}, @@ -169,7 +171,7 @@ "name": "location", "parser": { "prog": "sqb location", - "description": "Compile and publish a project from its own Python environment. Uses SQLBUILD_LOCATION_TOKEN for scoped HTTP access, never the control database. Results are JSON; progress goes to stderr.", + "description": "Compile and publish a project from its own Python environment. Uses SQLBUILD_LOCATION_TOKEN for scoped HTTP access, never the control database; republish instead uses SQLBUILD_API_KEY, over HTTP or HTTPS, or your sqb login session, over HTTPS. Results are JSON; progress goes to stderr.", "groups": [ { "title": "positional arguments" @@ -193,8 +195,8 @@ "options": [], "dest": "location_command", "required": true, - "choices": ["publish", "serve", "health", "runtime", "execute"], - "help": "publish one snapshot, watch and reload, check health (exits 1 when the location is down or its last load failed), or run the supervisor's stdio compiler", + "choices": ["publish", "serve", "health", "republish", "runtime", "execute"], + "help": "publish one snapshot, watch and reload, check health (exits 1 when the location is down or its last load failed), ask a served location to republish, or run the supervisor's stdio compiler", "group": 0 }, { @@ -243,6 +245,38 @@ "help": "for serve, sync the warehouse at least this often, such as 30m; 0 or off turns it off", "group": 1 }, + { + "kind": "store", + "options": ["--reason"], + "dest": "location_reason", + "help": "for republish, why, as the audit log and the location record it", + "group": 1 + }, + { + "kind": "store_true", + "options": ["--wait"], + "dest": "location_wait", + "nargs": 0, + "const": true, + "default": false, + "help": "for republish, wait for the new snapshot or the publish error", + "group": 1 + }, + { + "kind": "store", + "options": ["--timeout"], + "dest": "location_timeout", + "type": "int", + "help": "for republish --wait, seconds to wait (default: 600)", + "group": 1 + }, + { + "kind": "store", + "options": ["--ca-cert"], + "dest": "login_ca", + "help": "for republish with a sqb login session, an additional trusted PEM CA certificate", + "group": 1 + }, { "kind": "store", "options": ["--run-id"], @@ -272,7 +306,7 @@ "name": "admin", "parser": { "prog": "sqb admin", - "description": "Privileged local administration using direct control database access. Results are JSON; issued bearer credentials appear only once on stdout.", + "description": "Privileged local administration using direct control database access. Each command says what it did in one line on stderr; stdout holds only an issued secret, shown once, or the rows of a read, or only the JSON result with --json.", "groups": [ { "title": "positional arguments" @@ -348,7 +382,9 @@ "required": true, "help": "location label; identity is assigned by the control store", "group": 0 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -387,7 +423,9 @@ "required": true, "help": "principal label; creation grants no permissions", "group": 0 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -399,7 +437,9 @@ "groups": [{"title": "positional arguments"}, {"title": "options"}], "actions": [ {"kind": "help", "options": ["-h", "--help"], "dest": "help", "nargs": 0, "default": {"suppress": true}, "help": "show this help message and exit", "group": 1}, - {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "PRINCIPAL_ID", "required": true, "help": "active person UUID; password is read from the terminal or standard input, never an argument", "group": 0} + {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "PRINCIPAL_ID", "required": true, "help": "active person UUID; password is read from the terminal or standard input, never an argument", "group": 0}, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -411,7 +451,9 @@ "groups": [{"title": "positional arguments"}, {"title": "options"}], "actions": [ {"kind": "help", "options": ["-h", "--help"], "dest": "help", "nargs": 0, "default": {"suppress": true}, "help": "show this help message and exit", "group": 1}, - {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "NAME", "required": true, "help": "first administrator's person name", "group": 0} + {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "NAME", "required": true, "help": "first administrator's person name", "group": 0}, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -423,7 +465,9 @@ "groups": [{"title": "positional arguments"}, {"title": "options"}], "actions": [ {"kind": "help", "options": ["-h", "--help"], "dest": "help", "nargs": 0, "default": {"suppress": true}, "help": "show this help message and exit", "group": 1}, - {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "PRINCIPAL_ID", "required": true, "help": "existing person UUID to enable and grant installation admin", "group": 0} + {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "PRINCIPAL_ID", "required": true, "help": "existing person UUID to enable and grant installation admin", "group": 0}, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -472,7 +516,9 @@ "required": true, "help": "future expiry as an RFC3339 timestamp with timezone", "group": 1 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -511,7 +557,9 @@ "required": true, "help": "credential UUID, never its bearer secret", "group": 0 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -519,11 +567,13 @@ "name": "rotate-token", "parser": { "prog": "sqb admin rotate-token", - "description": "Replace a live credential atomically through direct control-store ownership, retaining its exact scope and expiry. Returns the new bearer once as JSON; the old credential immediately stops working.", + "description": "Replace a live credential atomically through direct control-store ownership, retaining its exact scope and expiry. Prints the new bearer once, alone on stdout; the old credential immediately stops working.", "groups": [{"title": "positional arguments"}, {"title": "options"}], "actions": [ {"kind": "help", "options": ["-h", "--help"], "dest": "help", "nargs": 0, "default": {"suppress": true}, "help": "show this help message and exit", "group": 1}, - {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "TOKEN_ID", "required": true, "help": "live credential UUID, never its bearer secret", "group": 0} + {"kind": "store", "options": [], "dest": "admin_subject", "metavar": "TOKEN_ID", "required": true, "help": "live credential UUID, never its bearer secret", "group": 0}, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -574,7 +624,7 @@ "nargs": 0, "const": true, "default": false, - "help": "retry exactly the failed and skipped nodes, excluding successful nodes", + "help": "retry exactly the failed, cancelled, skipped and unreached nodes, excluding successful nodes", "group": 1 }, { @@ -592,7 +642,9 @@ "required": true, "help": "nonblank reason recorded with the security audit", "group": 1 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -727,7 +779,9 @@ "required": true, "help": "nonblank reason recorded with the security audit", "group": 1 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -782,7 +836,9 @@ "required": true, "help": "nonblank reason recorded with the security audit", "group": 1 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -813,7 +869,9 @@ "required": true, "help": "location work request UUID", "group": 0 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -873,7 +931,9 @@ "required": true, "help": "nonblank reason recorded with the cancellation fact and security audit", "group": 1 - } + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } }, @@ -968,7 +1028,255 @@ "dest": "admin_sensor_event", "help": "the sensor event ID to mark delivered without calling the function; required only for skip-event", "group": 1 + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} + ] + } + }, + { + "name": "create-service-account", + "parser": { + "prog": "sqb admin create-service-account", + "description": "Add a service account with a built-in role everywhere and print its API key once, alone on stdout; store it now, it isn't shown again. Only the key's hash is kept.", + "groups": [ + { + "title": "positional arguments" + }, + { + "title": "options" + } + ], + "actions": [ + { + "kind": "help", + "options": [ + "-h", + "--help" + ], + "dest": "help", + "nargs": 0, + "default": { + "suppress": true + }, + "help": "show this help message and exit", + "group": 1 + }, + { + "kind": "store", + "options": [], + "dest": "admin_subject", + "metavar": "NAME", + "required": true, + "help": "new service account name: 2 to 63 lowercase letters, digits, - or _, starting with a letter", + "group": 0 + }, + { + "kind": "store", + "options": [ + "--role" + ], + "dest": "admin_role", + "choices": [ + "viewer", + "operator", + "developer", + "admin" + ], + "required": true, + "help": "built-in role everywhere", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--description" + ], + "dest": "admin_description", + "help": "what uses it, shown in the Service accounts tab", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--key-from-env" + ], + "dest": "admin_key_env", + "metavar": "VAR", + "help": "import the key held in environment variable VAR instead of generating one, for setups that recreate a control store and must keep the same key: sqbk_ and at least 32 more characters, generated randomly (for example sqbk_ and 40 random letters and digits), since the key is only as strong as you make it; the result then omits the key", + "group": 1 + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} + ] + } + }, + { + "name": "rotate-service-account", + "parser": { + "prog": "sqb admin rotate-service-account", + "description": "Issue a service account a new API key, printed once, alone on stdout; the replaced key stops now unless --overlap-minutes keeps it working a little longer.", + "groups": [ + { + "title": "positional arguments" + }, + { + "title": "options" } + ], + "actions": [ + { + "kind": "help", + "options": [ + "-h", + "--help" + ], + "dest": "help", + "nargs": 0, + "default": { + "suppress": true + }, + "help": "show this help message and exit", + "group": 1 + }, + { + "kind": "store", + "options": [], + "dest": "admin_subject", + "metavar": "NAME", + "required": true, + "help": "service account name", + "group": 0 + }, + { + "kind": "store", + "options": [ + "--overlap-minutes" + ], + "dest": "admin_overlap_minutes", + "type": "int", + "help": "minutes the replaced key keeps working, 0 to 1440 (default: 0)", + "group": 1 + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} + ] + } + }, + { + "name": "disable-service-account", + "parser": { + "prog": "sqb admin disable-service-account", + "description": "Refuse every key of a service account at once.", + "groups": [ + { + "title": "positional arguments" + }, + { + "title": "options" + } + ], + "actions": [ + { + "kind": "help", + "options": [ + "-h", + "--help" + ], + "dest": "help", + "nargs": 0, + "default": { + "suppress": true + }, + "help": "show this help message and exit", + "group": 1 + }, + { + "kind": "store", + "options": [], + "dest": "admin_subject", + "metavar": "NAME", + "required": true, + "help": "service account name", + "group": 0 + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} + ] + } + }, + { + "name": "enable-service-account", + "parser": { + "prog": "sqb admin enable-service-account", + "description": "Accept a disabled service account's keys again.", + "groups": [ + { + "title": "positional arguments" + }, + { + "title": "options" + } + ], + "actions": [ + { + "kind": "help", + "options": [ + "-h", + "--help" + ], + "dest": "help", + "nargs": 0, + "default": { + "suppress": true + }, + "help": "show this help message and exit", + "group": 1 + }, + { + "kind": "store", + "options": [], + "dest": "admin_subject", + "metavar": "NAME", + "required": true, + "help": "service account name", + "group": 0 + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} + ] + } + }, + { + "name": "list-service-accounts", + "parser": { + "prog": "sqb admin list-service-accounts", + "description": "List service accounts with their roles and the prefixes of their working keys, never the keys.", + "groups": [ + { + "title": "positional arguments" + }, + { + "title": "options" + } + ], + "actions": [ + { + "kind": "help", + "options": [ + "-h", + "--help" + ], + "dest": "help", + "nargs": 0, + "default": { + "suppress": true + }, + "help": "show this help message and exit", + "group": 1 + }, + {"kind": "store_true", "options": ["--json"], "dest": "json", "nargs": 0, "const": true, "default": false, "help": "print only the JSON result, on stdout", "group": 1}, + {"kind": "store_true", "options": ["--verbose", "-v"], "dest": "verbose", "nargs": 0, "const": true, "default": false, "help": "also say when the control store opens and is ready", "group": 1} ] } } @@ -997,7 +1305,7 @@ { "dest": "issue-location-token", "metavar": "issue-location-token", - "help": "issue a bounded location credential, returned once as JSON" + "help": "issue a bounded location credential, printed once on stdout" }, { "dest": "revoke-token", @@ -1017,7 +1325,7 @@ { "dest": "rerun-run", "metavar": "rerun-run", - "help": "retry a terminal run or exactly its failed and skipped nodes" + "help": "retry a terminal run or exactly its unfinished nodes" }, { "dest": "cancel-run", @@ -1038,6 +1346,31 @@ "dest": "change-trigger", "metavar": "change-trigger", "help": "change trigger status or cursor with an atomic audit and retry identity" + }, + { + "dest": "create-service-account", + "metavar": "create-service-account", + "help": "add a service account with a role; its API key is printed once" + }, + { + "dest": "rotate-service-account", + "metavar": "rotate-service-account", + "help": "issue a service account a new API key, printed once" + }, + { + "dest": "disable-service-account", + "metavar": "disable-service-account", + "help": "refuse every key of a service account at once" + }, + { + "dest": "enable-service-account", + "metavar": "enable-service-account", + "help": "accept a disabled service account's keys again" + }, + { + "dest": "list-service-accounts", + "metavar": "list-service-accounts", + "help": "list service accounts and their key prefixes" } ] } @@ -1397,6 +1730,18 @@ "help": "Bypass the compile analysis cache for this invocation", "group": 1 }, + { + "kind": "store_true", + "options": [ + "--discover" + ], + "dest": "discover", + "nargs": 0, + "const": true, + "default": false, + "help": "Run the project's @discover functions with the target's providers for this command instead of compiling each for_each asset as its placeholder; nothing is saved", + "group": 1 + }, { "kind": "store", "options": [ @@ -1854,6 +2199,18 @@ "help": "Bypass the compile analysis cache for this invocation", "group": 1 }, + { + "kind": "store_true", + "options": [ + "--discover" + ], + "dest": "discover", + "nargs": 0, + "const": true, + "default": false, + "help": "Run the project's @discover functions with the target's providers for this command instead of compiling each for_each asset as its placeholder; nothing is saved", + "group": 1 + }, { "kind": "store", "options": [ @@ -2314,6 +2671,18 @@ "help": "Bypass the compile analysis cache for this invocation", "group": 1 }, + { + "kind": "store_true", + "options": [ + "--discover" + ], + "dest": "discover", + "nargs": 0, + "const": true, + "default": false, + "help": "Run the project's @discover functions with the target's providers for this command instead of compiling each for_each asset as its placeholder; nothing is saved", + "group": 1 + }, { "kind": "store", "options": [ diff --git a/crates/sqlbuild-cli/src/argv/constants.rs b/crates/sqlbuild-cli/src/argv/constants.rs index 88245da71b..fab4aaa541 100644 --- a/crates/sqlbuild-cli/src/argv/constants.rs +++ b/crates/sqlbuild-cli/src/argv/constants.rs @@ -77,7 +77,7 @@ pub(crate) const INT_CONVERTER: &str = "int"; pub(crate) const PATH_CONVERTER: &str = "Path"; /// Every `CliNamespace` attribute with a default, in declaration order. -pub(crate) const CLI_NAMESPACE_DEFAULTS: [(&str, NamespaceDefault); 194] = [ +pub(crate) const CLI_NAMESPACE_DEFAULTS: [(&str, NamespaceDefault); 195] = [ ("command", NamespaceDefault::None), ("project_dir", NamespaceDefault::None), ("dbt_project_dir", NamespaceDefault::None), @@ -90,6 +90,7 @@ pub(crate) const CLI_NAMESPACE_DEFAULTS: [(&str, NamespaceDefault); 194] = [ ("skip_dbt_debug", NamespaceDefault::Bool(false)), ("no_sql_validation", NamespaceDefault::Bool(false)), ("no_cache", NamespaceDefault::Bool(false)), + ("discover", NamespaceDefault::Bool(false)), ("allow_missing_secrets", NamespaceDefault::Bool(false)), ("defer_to", NamespaceDefault::None), ("defer_clone_from", NamespaceDefault::None), diff --git a/crates/sqlbuild-cli/src/argv/main/command_takes_option.rs b/crates/sqlbuild-cli/src/argv/main/command_takes_option.rs new file mode 100644 index 0000000000..5d2269378d --- /dev/null +++ b/crates/sqlbuild-cli/src/argv/main/command_takes_option.rs @@ -0,0 +1,31 @@ +//! Whether one command's parser defines an option. + +use crate::argv::_helpers::table::command_parser; +use crate::argv::models::ParserSpec; + +/// Whether the command at `path`, such as `["rules", "run"]`, defines an option written to `dest`. +#[must_use] +pub fn command_takes_option(path: &[&str], dest: &str) -> bool { + let Some((command, nested)) = path.split_first() else { + return false; + }; + let Ok(mut parser) = command_parser(command) else { + return false; + }; + for name in nested { + let child: Option<&ParserSpec> = parser + .actions + .iter() + .flat_map(|action| &action.parsers) + .find(|(subcommand, _)| subcommand == name) + .map(|(_, child)| child); + let Some(child) = child else { + return false; + }; + parser = child; + } + parser + .actions + .iter() + .any(|action| action.dest.as_deref() == Some(dest)) +} diff --git a/crates/sqlbuild-cli/src/argv/main/mod.rs b/crates/sqlbuild-cli/src/argv/main/mod.rs index 8916c50ed8..a56b03a2ec 100644 --- a/crates/sqlbuild-cli/src/argv/main/mod.rs +++ b/crates/sqlbuild-cli/src/argv/main/mod.rs @@ -2,6 +2,7 @@ pub mod accepted_settings_arguments; pub mod cli_namespace_defaults; pub(crate) mod command_project_and_target; pub mod command_settings_arguments; +pub mod command_takes_option; pub mod given_setting_dests; pub mod job_run_arguments; pub mod job_settings_arguments; diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs index d3f621d30d..0e22d1fab5 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs @@ -6,8 +6,8 @@ use sqlbuild_core::screen_text::models::PhaseState; use crate::dev_screen::_helpers::lines::{compose, ready_lines}; use crate::dev_screen::_helpers::transitions::{ - child_event, client_text, key_pressed, logged, run_cancelling, run_reported, service_stopped, - step_failed, step_finished, step_started, warehouse_settled, + child_event, client_text, exposed, key_pressed, logged, run_cancelling, run_reported, + service_stopped, step_failed, step_finished, step_started, warehouse_settled, }; use crate::dev_screen::models::{DevScreen, ScreenAction, ScreenMessage, ScreenOutput}; @@ -31,6 +31,7 @@ pub(crate) fn apply_screen_message( } => step_failed(screen, (step, detail, problem), now), ScreenMessage::Child(event) => child_event(screen, event, now, clock), ScreenMessage::Location(location) => (DevScreen { location, ..screen }, Vec::new()), + ScreenMessage::Exposed(who) => exposed(screen, who), ScreenMessage::Triggers(triggers) => (DevScreen { triggers, ..screen }, Vec::new()), ScreenMessage::Warehouse { adapter, state } => { warehouse_settled(screen, (adapter, state), now, clock) diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs index 9d80fae738..c9da439dfd 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs @@ -45,6 +45,13 @@ pub(crate) fn ready_lines(mut screen: DevScreen) -> (DevScreen, Vec) { let parts: Vec = warehouse_parts(&screen.adapter, &warehouse); if !screen.live { let mut lines: Vec = vec![format!("\u{2713} ready {}", screen.ui_url)]; + if !screen.exposure.is_empty() { + lines.extend(render_labelled_parts( + "access ", + std::slice::from_ref(&screen.exposure), + screen.facts.columns, + )); + } lines.extend(render_labelled_parts( "warehouse", &parts, @@ -97,6 +104,14 @@ pub(crate) fn ready_lines(mut screen: DevScreen) -> (DevScreen, Vec) { link: None, }, ]; + if !screen.exposure.is_empty() { + let access: BoxRow = BoxRow { + label: "Access".to_owned(), + parts: vec![screen.exposure.clone()], + link: None, + }; + rows.insert(1, access); + } if !screen.triggers.is_empty() { rows.push(BoxRow { label: "Triggers".to_owned(), @@ -111,6 +126,13 @@ pub(crate) fn ready_lines(mut screen: DevScreen) -> (DevScreen, Vec) { link: None, }); } + if let Some(discovered) = &screen.discovered { + rows.push(BoxRow { + label: "Discovered".to_owned(), + parts: discovered.split(" \u{b7} ").map(str::to_owned).collect(), + link: None, + }); + } let lines: Vec = render_ready_box(&rows, &screen.facts); (screen, lines) } diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs index 611e8378b1..d68f6de0db 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs @@ -14,9 +14,11 @@ pub(crate) fn new_dev_screen(setup: ScreenSetup) -> DevScreen { header: setup.header, header_printed: false, ui_url: String::new(), + exposure: String::new(), location: String::new(), env_file: setup.env_file, missing_secrets: Vec::new(), + secrets_env_file: None, triggers: String::new(), steps: STEPS.into_iter().map(pending).collect(), ready: false, @@ -26,6 +28,7 @@ pub(crate) fn new_dev_screen(setup: ScreenSetup) -> DevScreen { pending_changes: 0, serving: None, compile_detail: String::new(), + discovered: None, project_root: setup.project_root, prompt: None, client_partial: false, diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/secrets.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/secrets.rs index 64b169a5fd..3bf38ee092 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/secrets.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/secrets.rs @@ -1,13 +1,22 @@ -//! The warning `sqb dev` shows while providers miss secrets: their variables and how to set them, until a health read shows none. +//! What `sqb dev` shows while providers miss secrets: a warning block when that changes, and a row until a health read shows none. +use std::collections::BTreeSet; + +use sqlbuild_core::screen_text::main::render_problem::render_problem; use sqlbuild_core::screen_text::main::render_step_line::render_step_line; -use sqlbuild_core::screen_text::models::{PhaseState, StepLine}; +use sqlbuild_core::screen_text::models::{ + PhaseState, Problem, ProblemLevel, Segment, StepLine, Tone, +}; +use sqlbuild_core::text::main::cell_len::cell_len; use sqlbuild_orchestration::dev_events::models::UnsetProviderSecrets; -use crate::dev_screen::constants::{SECRETS_FIX, SECRETS_MISSING, SECRETS_SET}; +use crate::dev_screen::constants::{ + SECRETS_CODE, SECRETS_MISSING, SECRETS_NODES_SHOWN, SECRETS_PLACE_MARGIN, SECRETS_SET, + SECRETS_WIDE_COLUMNS, +}; use crate::dev_screen::models::DevScreen; -/// Each provider and the variables it misses, then how to set them; empty when none is missing. +/// The live row while secrets are missing: each provider and the variables it misses; empty when none is. pub(crate) fn secrets_rows(screen: &DevScreen) -> Vec { if screen.missing_secrets.is_empty() { return Vec::new(); @@ -15,32 +24,34 @@ pub(crate) fn secrets_rows(screen: &DevScreen) -> Vec { let providers: Vec = screen .missing_secrets .iter() - .map(|provider| format!("{} {}", provider.provider, provider.variables.join(", "))) + .map(|provider| format!("{} {}", provider.provider, variables(provider).join(", "))) .collect(); let line: StepLine = StepLine { state: PhaseState::Warn, label: SECRETS_MISSING.to_owned(), elapsed: None, - detail: format!("{}; {SECRETS_FIX}", providers.join(" \u{b7} ")), + detail: providers.join(" \u{b7} "), }; render_step_line(&line, &screen.facts, true) } -/// Take the latest health read's providers missing secrets. A live screen redraws its warning row; a plain one prints the warning when it changes and a line when it clears. +/// Take the latest health read's providers missing secrets: the block when which are missing or the file changes, and one line once none is. pub(crate) fn secrets_reported( mut screen: DevScreen, providers: Vec, + env_file: Option, ) -> (DevScreen, Vec) { - if providers == screen.missing_secrets { - return (screen, Vec::new()); - } + let unchanged: bool = + unset(&providers) == unset(&screen.missing_secrets) && env_file == screen.secrets_env_file; let had_missing: bool = !screen.missing_secrets.is_empty(); screen.missing_secrets = providers; - if screen.live { - return (screen, Vec::new()); - } + screen.secrets_env_file = env_file; if !screen.missing_secrets.is_empty() { - let lines: Vec = secrets_rows(&screen); + let lines: Vec = if unchanged { + Vec::new() + } else { + render_problem(&secrets_problem(&screen), &screen.facts) + }; return (screen, lines); } if !had_missing { @@ -55,3 +66,128 @@ pub(crate) fn secrets_reported( let lines: Vec = render_step_line(&line, &screen.facts, true); (screen, lines) } + +fn variables(provider: &UnsetProviderSecrets) -> Vec<&str> { + provider + .settings + .iter() + .map(|setting| setting.variable.as_str()) + .collect() +} + +/// Which variables which providers miss, which is what a new block is printed for. +fn unset(providers: &[UnsetProviderSecrets]) -> Vec<(&str, Vec<&str>)> { + providers + .iter() + .map(|provider| (provider.provider.as_str(), variables(provider))) + .collect() +} + +/// The warning block: each field's file and line, why it matters with the nodes it stops, and the fix. +fn secrets_problem(screen: &DevScreen) -> Problem { + let providers: &[UnsetProviderSecrets] = &screen.missing_secrets; + let title: String = match providers.len() { + 1 => "1 provider has missing secrets".to_owned(), + count => format!("{count} providers have missing secrets"), + }; + let settings: usize = providers + .iter() + .map(|provider| provider.settings.len()) + .sum(); + Problem { + level: ProblemLevel::Warning, + title, + code: SECRETS_CODE.to_owned(), + at: places(providers, screen.facts.columns), + why: reason(providers), + fix: secrets_fix(settings, screen.secrets_env_file.as_deref()), + } +} + +/// `providers/payments.py:14 api_token \u{2190} PAYMENTS_API_TOKEN` per setting, in columns, or on two rows where that doesn't fit. +fn places(providers: &[UnsetProviderSecrets], columns: usize) -> Vec { + let label: &str = if columns >= SECRETS_WIDE_COLUMNS { + "field " + } else { + "" + }; + let mut places: Vec<(String, String, &str)> = Vec::new(); + for provider in providers { + for setting in &provider.settings { + let file: String = match setting.line { + Some(line) => format!("{}:{line}", provider.path), + None => provider.path.clone(), + }; + places.push((file, format!("{label}{}", setting.field), &setting.variable)); + } + } + let file_width: usize = places + .iter() + .map(|place| cell_len(&place.0)) + .max() + .unwrap_or(0); + let field_width: usize = places + .iter() + .map(|place| cell_len(&place.1)) + .max() + .unwrap_or(0); + let width: usize = columns.saturating_sub(SECRETS_PLACE_MARGIN); + let mut rows: Vec = Vec::new(); + for (file, field, variable) in places { + let row: String = + format!("{file: String { + let them: &str = if providers.len() == 1 { "it" } else { "them" }; + let reason: String = + format!("runs that use {them} stop at the provider check, before the warehouse"); + let mut seen: BTreeSet<&str> = BTreeSet::new(); + let mut names: Vec<&str> = Vec::new(); + for key in providers.iter().flat_map(|provider| &provider.needed_by) { + if seen.insert(key) { + names.push(key.split_once(':').map_or(key.as_str(), |(_, name)| name)); + } + } + let total: usize = names.len(); + if total == 0 { + return reason; + } + names.truncate(SECRETS_NODES_SHOWN); + let mut listed: String = names.join(", "); + if total > names.len() { + listed.push_str(&format!(" and {} more", total - names.len())); + } + let needing: String = if total == 1 { + "1 node needs".to_owned() + } else { + format!("{total} nodes need") + }; + format!("{reason}; {needing} {them} ({listed})") +} + +/// `r` re-reads an edited env file; only a new `sqb dev` sees a changed environment. +fn secrets_fix(settings: usize, env_file: Option<&str>) -> String { + let them: &str = if settings == 1 { "it" } else { "them" }; + let environment: String = format!( + "set {them} in the environment you start sqb dev from, then quit and run sqb dev again" + ); + match env_file { + Some(file) => format!("set {them} in {file} and press r, or {environment}"), + None => environment, + } +} diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs index 5dff7cb7e7..3235018141 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs @@ -17,7 +17,7 @@ use crate::dev_screen::_helpers::labels::elapsed_since; use crate::dev_screen::_helpers::lines::lasting_step; use crate::dev_screen::_helpers::rows::step_line; use crate::dev_screen::_helpers::secrets::secrets_reported; -use crate::dev_screen::constants::{LOG_RING_LINES, SIGN_IN_DETAIL, SNAPSHOT_ID_CHARS}; +use crate::dev_screen::constants::{LOG_RING_LINES, NO_SIGN_IN, SIGN_IN_DETAIL, SNAPSHOT_ID_CHARS}; use crate::dev_screen::models::{DevScreen, DevStep, Prompt, ScreenAction, StepRow}; /// The screen after a message, and the lines it prints for good. @@ -211,7 +211,28 @@ pub(crate) fn child_event( ); failed(screen, problem, now, clock) } - DevEvent::MissingSecrets { providers } => secrets_reported(screen, providers), + DevEvent::MissingSecrets { + providers, + env_file, + } => secrets_reported(screen, providers, env_file), + DevEvent::Discovered { summary } => { + let changed: bool = screen.discovered.as_ref() != Some(&summary); + let lines: Vec = if screen.ready && changed { + event_lines( + &screen, + event_line( + clock, + EventMark::Succeeded, + "discovered".to_owned(), + summary.clone(), + ), + ) + } else { + Vec::new() + }; + screen.discovered = Some(summary); + (screen, lines) + } DevEvent::Warning { title, detail } => { let lines: Vec = render_problem( &Problem { @@ -536,6 +557,20 @@ pub(crate) fn logged(mut screen: DevScreen, line: String) -> Printed { (screen, shown) } +/// The session is open beyond this machine: the warning printed for good, kept for the ready box and the log. +pub(crate) fn exposed(mut screen: DevScreen, who: String) -> Printed { + let line: StepLine = StepLine { + state: PhaseState::Warn, + label: NO_SIGN_IN.to_owned(), + elapsed: None, + detail: who.clone(), + }; + let lines: Vec = lasting_step(&screen, &line); + screen.log.push_back(format!("{NO_SIGN_IN}: {who}")); + screen.exposure = who; + (screen, lines) +} + /// What a key asks for; `l` toggles the log and opens it with the lines kept so far. pub(crate) fn key_pressed( mut screen: DevScreen, diff --git a/crates/sqlbuild-cli/src/dev_screen/constants.rs b/crates/sqlbuild-cli/src/dev_screen/constants.rs index 3514cd77ac..4e77d59718 100644 --- a/crates/sqlbuild-cli/src/dev_screen/constants.rs +++ b/crates/sqlbuild-cli/src/dev_screen/constants.rs @@ -45,9 +45,17 @@ pub(crate) const SUSPEND_BYTE: u8 = 0x1a; pub(crate) const SUSPEND_UNSUPPORTED: &str = "Ctrl+Z does not suspend sqb dev; press q to stop it, or Ctrl+C"; +/// The start-up warning's label when the session is open beyond this machine. +pub(crate) const NO_SIGN_IN: &str = "No sign-in"; /// The warning row's label while providers miss secrets. pub(crate) const SECRETS_MISSING: &str = "Secrets missing"; -/// What the warning row says to do about the missing secrets. -pub(crate) const SECRETS_FIX: &str = "set them in .env or the environment; press r to reload"; +/// The warning block's code. +pub(crate) const SECRETS_CODE: &str = "missing secret"; +/// The affected nodes the warning block names before `and N more`. +pub(crate) const SECRETS_NODES_SHOWN: usize = 5; +/// The columns from which the warning block labels each field with `field`. +pub(crate) const SECRETS_WIDE_COLUMNS: usize = 120; +/// The cells a problem block leaves before a place, and the last cell it keeps free. +pub(crate) const SECRETS_PLACE_MARGIN: usize = 10; /// The plain line once no provider misses a secret. pub(crate) const SECRETS_SET: &str = "Secrets set"; diff --git a/crates/sqlbuild-cli/src/dev_screen/models.rs b/crates/sqlbuild-cli/src/dev_screen/models.rs index 86519fb79c..a67e2b20e6 100644 --- a/crates/sqlbuild-cli/src/dev_screen/models.rs +++ b/crates/sqlbuild-cli/src/dev_screen/models.rs @@ -49,6 +49,8 @@ pub(crate) enum ScreenMessage { Child(DevEvent), /// The development location's ID, known once the control store is open; plain output prints it with `ready`. Location(String), + /// The session is open beyond this machine: who gets in without signing in. + Exposed(String), /// The dev target's triggers, such as `41 paused`, read after the first publication. Triggers(String), /// The foreground warehouse connection's outcome. @@ -136,11 +138,15 @@ pub(crate) struct DevScreen { pub(crate) header: DevHeader, pub(crate) header_printed: bool, pub(crate) ui_url: String, + /// Who gets in without signing in; empty for a loopback-only session. + pub(crate) exposure: String, pub(crate) location: String, /// The env file row of the ready box. pub(crate) env_file: Option, /// Providers the latest health read shows missing secrets; drawn as a warning row until a read shows none. pub(crate) missing_secrets: Vec, + /// The env file that health read looked in. + pub(crate) secrets_env_file: Option, pub(crate) triggers: String, pub(crate) steps: Vec, pub(crate) ready: bool, @@ -154,6 +160,8 @@ pub(crate) struct DevScreen { pub(crate) serving: Option, /// The last compile's summary, such as `412 python nodes, 2280 models`. pub(crate) compile_detail: String, + /// The last publication's discovered sets, such as `orders_plan 27 items`. + pub(crate) discovered: Option, /// The project directory, which error positions link into. pub(crate) project_root: String, pub(crate) prompt: Option, diff --git a/crates/sqlbuild-cli/src/dev_screen/tests.rs b/crates/sqlbuild-cli/src/dev_screen/tests.rs index f7f1cd1d05..afbc4c02c6 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests.rs @@ -1,5 +1,9 @@ #[path = "tests/test_apply_screen_message.rs"] mod apply_screen_message; +#[path = "tests/test_discovered.rs"] +mod discovered; +#[path = "tests/test_exposure.rs"] +mod exposure; #[path = "tests/helpers.rs"] mod helpers; #[path = "tests/test_missing_secrets.rs"] diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs index 046fc5734c..ec5e86b2ce 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs @@ -10,6 +10,7 @@ use sqlbuild_core::text::main::cell_len::cell_len; use sqlbuild_orchestration::dev_events::models::{ DevEvent, DevPhase, DevStepState, SourcePosition, UnsetProviderSecrets, }; +use sqlbuild_orchestration::platform::models::MissingProviderSetting; use crate::dev_screen::_helpers::apply_screen_message::apply_screen_message; use crate::dev_screen::_helpers::drawing::closing_text; @@ -144,7 +145,10 @@ pub(super) fn ready() -> Vec { } /// Start-up through the ready box, then one health read per report of the providers missing secrets. -pub(super) fn secrets_reported(reports: Vec)>>) -> Vec { +pub(super) fn secrets_reported( + reports: Vec)>>, + (env_file, needed_by): (Option<&str>, &[&str]), +) -> Vec { let mut messages: Vec = ready(); for report in reports { messages.push(ScreenMessage::Child(DevEvent::MissingSecrets { @@ -152,9 +156,20 @@ pub(super) fn secrets_reported(reports: Vec)>>) -> Vec Vec { }) .collect() } + +/// Start-up through the ready box on a session opened to every interface and one allowed name. +pub(super) fn opened() -> Vec { + let mut messages: Vec = ready(); + messages.insert( + 4, + ScreenMessage::Exposed( + "anyone who can reach 0.0.0.0:8640 or control.example.com has full, sign-in-free \ + access with your credentials" + .to_owned(), + ), + ); + messages +} + +/// Start-up that publishes discovered sets summarised as `summary`, through the ready box. +pub(super) fn discovered(summary: &str) -> Vec { + let mut messages: Vec = signing_in(); + messages.push(ScreenMessage::Child(DevEvent::Discovered { + summary: summary.to_owned(), + })); + messages.extend(ready().split_off(signing_in().len())); + messages +} diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_discovered.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_discovered.rs new file mode 100644 index 0000000000..b71324de08 --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_discovered.rs @@ -0,0 +1,29 @@ +//! A location's discovered sets are a row of the ready box. + +use crate::dev_screen::tests::helpers::{discovered, play, still_running}; +use crate::dev_screen::tests::test_types::DiscoveredRowTestCase; + +#[test] +fn given_discovered_sets_when_the_session_is_ready_then_the_box_has_their_row() { + let test_cases = [DiscoveredRowTestCase { + description: "two sets, one failing", + summary: "orders_plan 27 items \u{b7} returns_plan \u{2717} ssh timeout (using last good, 11 items)", + expected_lines: vec![ + "\u{2502} Discovered orders_plan 27 items", + "\u{2502} returns_plan \u{2717} ssh timeout (using last good, 11 items)", + ], + }]; + for test_case in test_cases { + let shown: String = play(Some((80, 24)), discovered(test_case.summary), still_running) + .scrollback + .join("\n"); + assert!( + test_case + .expected_lines + .iter() + .all(|line| shown.contains(line)), + "{}: {shown}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_exposure.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_exposure.rs new file mode 100644 index 0000000000..e569c8ba54 --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_exposure.rs @@ -0,0 +1,43 @@ +//! A session open beyond this machine says who gets in, at start-up and in the ready block. + +use crate::dev_screen::tests::helpers::{opened, play, still_running}; +use crate::dev_screen::tests::test_types::ExposureTestCase; + +#[test] +fn given_a_session_open_beyond_this_machine_when_it_starts_then_the_log_and_ready_block_say_who_gets_in() + { + let test_cases = [ + ExposureTestCase { + description: "live", + size: Some((80, 24)), + expected_lines: vec![ + "\u{26a0} No sign-in", + "anyone who can reach 0.0.0.0:8640", + "\u{2502} Access anyone who can reach 0.0.0.0:8640", + ], + }, + ExposureTestCase { + description: "plain", + size: None, + expected_lines: vec![ + "\u{26a0} No sign-in", + "anyone who can reach 0.0.0.0:8640", + " access anyone who can reach 0.0.0.0:8640", + ], + }, + ]; + for test_case in test_cases { + let shown: String = play(test_case.size, opened(), still_running) + .scrollback + .join("\n"); + assert!( + test_case + .expected_lines + .iter() + .all(|line| shown.contains(line)) + && shown.contains("credentials"), + "{}: {shown}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs index 73ba297adf..f8676f87cb 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs @@ -10,33 +10,62 @@ fn given_providers_missing_secrets_when_health_is_read_then_a_warning_names_them { let test_cases = [ MissingSecretsTestCase { - description: "a live screen draws the warning above the keys", + description: "a live screen prints the block and keeps a row above the keys", size: TALL, + env_file: Some("config/dev.env"), + needed_by: &["source:raw_regions", "model:stg_regions"], reports: vec![vec![("region", vec!["REGION_TOKEN", "REGION_CODE"])]], expected_tail: vec![ - "\u{2502} Triggers 41 paused \u{2502}", - "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", - "\u{26a0} Secrets missing region REGION_TOKEN, REGION_CODE; set them in", - " .env or the environment; press r to reload", + "\u{26a0} warn 1 provider has missing secrets missing secret", + " at providers/region.py:9 region_token \u{2190} REGION_TOKEN", + " providers/region.py:10 region_code \u{2190} REGION_CODE", + " why runs that use it stop at the provider check, before the warehouse; 2", + " nodes need it (raw_regions, stg_regions)", + " fix set them in config/dev.env and press r, or set them in the environment", + " you start sqb dev from, then quit and run sqb dev again", + "\u{26a0} Secrets missing region REGION_TOKEN, REGION_CODE", "keys o open UI \u{b7} l full log \u{b7} r recompile \u{b7} q quit", ], }, MissingSecretsTestCase { - description: "a live screen drops the warning once a read shows none", - size: TALL, - reports: vec![ - vec![("region", vec!["REGION_TOKEN", "REGION_CODE"])], - vec![], + description: "without an env file only a restart is offered, and a long node list is folded", + size: None, + env_file: None, + needed_by: &[ + "source:raw_regions", + "model:a", + "model:b", + "model:c", + "model:d", + "model:e", + "model:f", + ], + reports: vec![vec![("region", vec!["REGION_TOKEN"])]], + expected_tail: vec![ + "\u{26a0} warn 1 provider has missing secrets missing secret", + " at providers/region.py:9 region_token \u{2190} REGION_TOKEN", + " why runs that use it stop at the provider check, before the warehouse; 7", + " nodes need it (raw_regions, a, b, c, d and 2 more)", + " fix set it in the environment you start sqb dev from, then quit and run", + " sqb dev again", ], + }, + MissingSecretsTestCase { + description: "a live screen drops the row once a read shows none", + size: TALL, + env_file: Some(".env"), + needed_by: &[], + reports: vec![vec![("region", vec!["REGION_TOKEN"])], vec![]], expected_tail: vec![ - "\u{2502} Triggers 41 paused \u{2502}", - "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", + "\u{2713} Secrets set no provider is missing a secret", "keys o open UI \u{b7} l full log \u{b7} r recompile \u{b7} q quit", ], }, MissingSecretsTestCase { - description: "plain output prints the warning once per change, then that the secrets are set", + description: "plain output prints the block once per change, then that the secrets are set", size: None, + env_file: Some(".env"), + needed_by: &[], reports: vec![ vec![("region", vec!["REGION_TOKEN"])], vec![("region", vec!["REGION_TOKEN"])], @@ -45,8 +74,11 @@ fn given_providers_missing_secrets_when_health_is_read_then_a_warning_names_them ], expected_tail: vec![ " triggers 41 paused", - "\u{26a0} Secrets missing region REGION_TOKEN; set them in .env or the", - " environment; press r to reload", + "\u{26a0} warn 1 provider has missing secrets missing secret", + " at providers/region.py:9 region_token \u{2190} REGION_TOKEN", + " why runs that use it stop at the provider check, before the warehouse", + " fix set it in .env and press r, or set it in the environment you start sqb", + " dev from, then quit and run sqb dev again", "\u{2713} Secrets set no provider is missing a secret", ], }, @@ -55,7 +87,7 @@ fn given_providers_missing_secrets_when_health_is_read_then_a_warning_names_them for test_case in test_cases { let viewport: Vec = play( test_case.size, - secrets_reported(test_case.reports), + secrets_reported(test_case.reports, (test_case.env_file, test_case.needed_by)), still_running, ) .viewport; diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs index da423d21ab..93c301d18b 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs @@ -23,6 +23,10 @@ pub(super) struct ScreenTestCase { pub(super) struct MissingSecretsTestCase { pub(super) description: &'static str, pub(super) size: Option<(usize, usize)>, + /// The env file the location loads. + pub(super) env_file: Option<&'static str>, + /// The nodes that need each provider. + pub(super) needed_by: &'static [&'static str], /// Each health read's providers and the variables they miss, in order. pub(super) reports: Vec)>>, /// The last rows the terminal shows. @@ -119,3 +123,16 @@ pub(super) struct KeyTestCase { pub(super) keys: &'static str, pub(super) expected_actions: Vec, } + +/// An opened session at one size: what it keeps in the scrollback. +pub(super) struct DiscoveredRowTestCase { + pub(super) description: &'static str, + pub(super) summary: &'static str, + pub(super) expected_lines: Vec<&'static str>, +} + +pub(super) struct ExposureTestCase { + pub(super) description: &'static str, + pub(super) size: Option<(usize, usize)>, + pub(super) expected_lines: Vec<&'static str>, +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/delivery.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/delivery.rs new file mode 100644 index 0000000000..3aa5650dba --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/delivery.rs @@ -0,0 +1,26 @@ +//! Deliver an admin result: a secret, rows or JSON on stdout, then the line saying what was done on stderr. + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::admin::results::result_json; +use crate::native_commands::_helpers::admin::rows::stdout_text; +use crate::native_commands::_helpers::admin::summaries::summary_line; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::constants::ADMIN_DELIVERY_FAILED; +use crate::native_commands::models::AdminDone; + +/// Print `done` and return the exit status; the line follows only output that arrived. +pub(crate) fn deliver_admin_result(done: &AdminDone, json: bool) -> i32 { + let (stdout, summary): (String, Option) = if json { + (format!("{}\n", result_json(done)), None) + } else { + (stdout_text(done), summary_line(done)) + }; + if write_output(&[(Stream::Stdout, &stdout)]).is_some() { + drop(write_output(&[(Stream::Stderr, ADMIN_DELIVERY_FAILED)])); + return 1; + } + if let Some(summary) = summary { + drop(write_output(&[(Stream::Stderr, &format!("{summary}\n"))])); + } + 0 +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/mod.rs new file mode 100644 index 0000000000..7806942e62 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/mod.rs @@ -0,0 +1,7 @@ +pub(crate) mod delivery; +pub(crate) mod people; +pub(crate) mod requests; +pub(crate) mod results; +pub(crate) mod rows; +pub(crate) mod store; +pub(crate) mod summaries; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/people.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/people.rs new file mode 100644 index 0000000000..18b7c8f517 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/people.rs @@ -0,0 +1,32 @@ +//! Commands that change a person by ID and say whom they changed. + +use sqlbuild_orchestration::authorization::main::roles::grant_admin::grant_admin; +use sqlbuild_orchestration::credentials::main::sessions::set_password::set_password; +use sqlbuild_orchestration::credentials::models::{AuditContext, PasswordAuthority}; +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; +use uuid::Uuid; + +use crate::native_commands::_helpers::command::admin_actions::name_or_id; +use crate::native_commands::models::AdminDone; + +pub(crate) async fn provide_password( + store: &ControlStore, + context: &AuditContext, + (id, password): (Uuid, String), +) -> Result { + let name: String = name_or_id(store, id).await?; + let authority = PasswordAuthority::Operator(id); + set_password(store, context, authority, &password).await?; + Ok(AdminDone::PasswordSet { id, name }) +} + +pub(crate) async fn restore_admin( + store: &ControlStore, + context: &AuditContext, + id: Uuid, +) -> Result { + let name: String = name_or_id(store, id).await?; + grant_admin(store, context, id).await?; + Ok(AdminDone::AdminGranted { id, name }) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/requests.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/requests.rs new file mode 100644 index 0000000000..56411f51ca --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/requests.rs @@ -0,0 +1,109 @@ +//! Commands on runs, triggers and location requests, each with what to say about it. + +use sqlbuild_orchestration::credentials::models::AuditContext; +use sqlbuild_orchestration::declarations::main::change_trigger::change_trigger; +use sqlbuild_orchestration::declarations::models::TriggerChangeRequest; +use sqlbuild_orchestration::platform::main::work::location_work::location_work; +use sqlbuild_orchestration::platform::main::work::request_location_work::request_location_work; +use sqlbuild_orchestration::platform::models::LocationWorkRequest; +use sqlbuild_orchestration::runs::main::execution::change_run::change_run; +use sqlbuild_orchestration::runs::main::requests::request_job_run::request_job_run; +use sqlbuild_orchestration::runs::main::requests::request_rerun::request_rerun; +use sqlbuild_orchestration::runs::models::{ + JobRunRequest, RerunRequest, RunAuthority, RunChange, RunChangeRequest, +}; +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; +use uuid::Uuid; + +use crate::adhoc::main::adhoc_planner::adhoc_planner; +use crate::native_commands::_helpers::command::admin_actions::name_or_id; +use crate::native_commands::models::AdminDone; + +/// A trusted job run, narrowed with the same planner the server resolves ad-hoc commands with. +pub(crate) async fn queue_job_run( + store: &ControlStore, + context: &AuditContext, + request: JobRunRequest, +) -> Result { + let planner = adhoc_planner(); + let applied = request_job_run(store, (context, Some(planner.as_ref())), &request).await?; + Ok(AdminDone::RunQueued { + run_id: request.run_id, + job: request.job_key, + target: request.target, + applied, + }) +} + +pub(crate) async fn queue_rerun( + store: &ControlStore, + context: &AuditContext, + request: RerunRequest, +) -> Result { + Ok(AdminDone::RerunQueued { + run_id: request.run_id, + source: request.source_run_id, + applied: request_rerun(store, (context, None), &request).await?, + }) +} + +pub(crate) async fn request_check( + store: &ControlStore, + context: &AuditContext, + request: LocationWorkRequest, +) -> Result { + let location: String = name_or_id(store, request.location_id).await?; + Ok(AdminDone::CheckRequested { + location, + applied: request_location_work(store, (context, None), &request).await?, + request_id: request.request_id, + target: request.target, + }) +} + +pub(crate) async fn read_request( + store: &ControlStore, + request_id: Uuid, +) -> Result { + Ok(AdminDone::WorkRead { + request_id, + record: location_work(store, request_id).await?.map(Box::new), + now: chrono::Utc::now(), + }) +} + +pub(crate) async fn request_cancellation( + store: &ControlStore, + context: &AuditContext, + (event_id, run_id, reason): (Uuid, Uuid, String), +) -> Result { + let request = RunChangeRequest { + event_id, + run_id, + claim_id: None, + change: RunChange::CancelRequested { + actor: context.actor.clone(), + reason, + }, + }; + Ok(AdminDone::CancelRequested { + event_id, + run_id, + applied: change_run(store, RunAuthority::Operator(context), &request).await?, + }) +} + +pub(crate) async fn override_trigger( + store: &ControlStore, + context: &AuditContext, + request: TriggerChangeRequest, +) -> Result { + let applied: bool = change_trigger(store, context, &request).await?; + Ok(AdminDone::TriggerChanged { + event_id: request.event_id, + trigger_id: request.trigger_id, + change: request.change, + applied, + }) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/results.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/results.rs new file mode 100644 index 0000000000..3b2a6f3f17 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/results.rs @@ -0,0 +1,72 @@ +//! Each admin command's JSON result, which `--json` prints. + +use serde_json::{Value, json}; +use sqlbuild_orchestration::credentials::models::ServiceAccountSummary; + +use crate::native_commands::models::AdminDone; + +pub(crate) fn result_json(done: &AdminDone) -> Value { + match done { + AdminDone::Bootstrapped { id, name } => { + json!({"principal_id": id, "name": name, "kind": "person", "role": "admin"}) + } + AdminDone::LocationCreated { id, name } => json!({"location_id": id, "name": name}), + AdminDone::PrincipalCreated { id, name } => json!({"principal_id": id, "name": name}), + AdminDone::PasswordSet { id, .. } => json!({"principal_id": id, "password_set": true}), + AdminDone::AdminGranted { id, .. } => json!({"principal_id": id, "role": "admin"}), + AdminDone::TokenIssued { token, .. } | AdminDone::TokenRotated { token, .. } => { + json!(token) + } + AdminDone::TokenRevoked { id, revoked } => json!({"token_id": id, "revoked": revoked}), + AdminDone::RunQueued { + run_id, applied, .. + } + | AdminDone::RerunQueued { + run_id, applied, .. + } => { + json!({"run_id": run_id, "applied": applied}) + } + AdminDone::CheckRequested { + request_id, + applied, + .. + } => { + json!({"request_id": request_id, "applied": applied}) + } + AdminDone::WorkRead { record, .. } => json!(record), + AdminDone::CancelRequested { + event_id, + run_id, + applied, + } => { + json!({"event_id": event_id, "run_id": run_id, "applied": applied}) + } + AdminDone::TriggerChanged { + event_id, + trigger_id, + applied, + .. + } => { + json!({"event_id": event_id, "trigger_id": trigger_id, "applied": applied}) + } + AdminDone::AccountCreated { account, key } => key_result(account, key.as_ref()), + AdminDone::KeyRotated { account, key } => key_result(account, Some(key)), + AdminDone::AccountSwitched { account, .. } => json!(account), + AdminDone::AccountsListed(accounts) => json!(accounts), + } +} + +/// The account with its new key, or without one when the operator imported their own key. +fn key_result(account: &ServiceAccountSummary, key: Option<&String>) -> Value { + let mut result = json!({ + "principal_id": account.principal_id, + "name": account.name, + "role": account.role, + "key_prefix": account.keys.first().map(|key| &key.prefix), + "account": account, + }); + if let Some(key) = key { + result["key"] = json!(key); + } + result +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/rows.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/rows.rs new file mode 100644 index 0000000000..39e327fcbc --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/rows.rs @@ -0,0 +1,127 @@ +//! An admin command's stdout without `--json`: a bare secret, or a read's plain rows. + +use chrono::{DateTime, SecondsFormat, Utc}; +use serde_json::json; +use sqlbuild_core::text::main::cell_len::cell_len; +use sqlbuild_orchestration::credentials::models::ServiceAccountSummary; +use sqlbuild_orchestration::platform::models::{LocationWorkOutcome, LocationWorkRecord}; + +use crate::native_commands::_helpers::admin::summaries::{printable, role_text}; +use crate::native_commands::constants::NO_VALUE; +use crate::native_commands::models::AdminDone; + +/// Empty for a command that only did something, so nothing but a secret or a read reaches stdout. +pub(crate) fn stdout_text(done: &AdminDone) -> String { + match done { + AdminDone::TokenIssued { token, .. } | AdminDone::TokenRotated { token, .. } => { + format!("{}\n", token.bearer) + } + AdminDone::AccountCreated { key: Some(key), .. } | AdminDone::KeyRotated { key, .. } => { + format!("{key}\n") + } + AdminDone::WorkRead { + record: Some(record), + now, + .. + } => rows_text(work_rows(record, *now)), + AdminDone::AccountsListed(accounts) => { + rows_text(accounts.iter().map(account_row).collect()) + } + _ => String::new(), + } +} + +/// Name, role, state, the prefixes of working keys and the ID. +fn account_row(account: &ServiceAccountSummary) -> Vec { + let prefixes: Vec<&str> = account.keys.iter().map(|key| key.prefix.as_str()).collect(); + vec![ + account.name.clone(), + role_text(account.role), + if account.disabled_at.is_some() { + "disabled" + } else { + "active" + } + .to_owned(), + if prefixes.is_empty() { + NO_VALUE.to_owned() + } else { + prefixes.join(",") + }, + account.principal_id.to_string(), + ] +} + +/// One row per fact of a location request, its state derived at `now`. +fn work_rows(record: &LocationWorkRecord, now: DateTime) -> Vec> { + let request = &record.request_json; + let state: &str = if record.completed_at.is_some() { + "completed" + } else if record.expires_at <= now { + "expired" + } else { + "waiting" + }; + let outcome: String = record.result_json.as_ref().map_or_else( + || NO_VALUE.to_owned(), + |result| match &result.outcome { + LocationWorkOutcome::Connection { healthy: true } => "connection healthy".to_owned(), + LocationWorkOutcome::Connection { healthy: false } => "connection failed".to_owned(), + outcome => kind_text(&json!(outcome)), + }, + ); + let completed: String = record + .completed_at + .map_or_else(|| NO_VALUE.to_owned(), time_text); + [ + ("request_id", request.request_id.to_string()), + ("work", kind_text(&json!(request.work))), + ("location_id", request.location_id.to_string()), + ("target", request.target.clone()), + ("state", state.to_owned()), + ("outcome", outcome), + ("requested_by", record.requested_by.clone()), + ("requested_at", time_text(record.requested_at)), + ("expires_at", time_text(record.expires_at)), + ("completed_at", completed), + ("reason", request.reason.clone()), + ] + .into_iter() + .map(|(name, value)| vec![name.to_owned(), value]) + .collect() +} + +fn kind_text(value: &serde_json::Value) -> String { + value["kind"].as_str().unwrap_or(NO_VALUE).to_owned() +} + +fn time_text(time: DateTime) -> String { + time.to_rfc3339_opts(SecondsFormat::Secs, true) +} + +/// Columns two spaces apart, with no header and one line per row. +fn rows_text(rows: Vec>) -> String { + let cells: Vec> = rows.iter().map(|row| printable_row(row)).collect(); + let mut widths: Vec = Vec::new(); + for row in &cells { + widths.resize(widths.len().max(row.len()), 0); + for (width, cell) in widths.iter_mut().zip(row) { + *width = (*width).max(cell_len(cell)); + } + } + let mut text: String = String::new(); + for row in &cells { + let mut line: String = String::new(); + for (width, cell) in widths.iter().zip(row) { + line.push_str(cell); + line.push_str(&" ".repeat(width - cell_len(cell) + 2)); + } + text.push_str(line.trim_end()); + text.push('\n'); + } + text +} + +fn printable_row(row: &[String]) -> Vec { + row.iter().map(|cell| printable(cell)).collect() +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/store.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/store.rs new file mode 100644 index 0000000000..9bcd4cf8e1 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/store.rs @@ -0,0 +1,34 @@ +//! `sqb admin` opens its store quietly, unless asked to say so or opening is slow. + +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; + +use crate::argv::models::{Namespace, Stream}; +use crate::native_commands::_helpers::command::decision::{ + control_database, control_database_variable, flag, +}; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::execution::open_migrated_store; +use crate::native_commands::constants::{ADMIN_OPEN_NOTICE, OPENING_STORE, STORE_READY}; +use crate::server_config::models::ServerSection; + +/// Open and migrate the store, announcing it with `--verbose` or once it takes noticeably long. +pub(crate) async fn open_admin_store(namespace: &Namespace) -> Result { + let url: String = control_database( + namespace, + &control_database_variable(namespace, &ServerSection::default()), + )?; + let opening = open_migrated_store(&url); + tokio::pin!(opening); + if !flag(namespace, "verbose") { + tokio::select! { + biased; + opened = &mut opening => return opened, + () = tokio::time::sleep(ADMIN_OPEN_NOTICE) => {} + } + } + drop(write_output(&[(Stream::Stderr, OPENING_STORE)])); + let store: ControlStore = opening.await?; + drop(write_output(&[(Stream::Stderr, STORE_READY)])); + Ok(store) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/admin/summaries.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/summaries.rs new file mode 100644 index 0000000000..2e280af5ce --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/admin/summaries.rs @@ -0,0 +1,191 @@ +//! The one line each admin command prints for what it did; never a secret. + +use chrono::{DateTime, SecondsFormat, Utc}; +use sqlbuild_orchestration::credentials::models::{BuiltinRole, ServiceAccountSummary}; +use sqlbuild_orchestration::declarations::models::TriggerChange; + +use crate::native_commands::constants::NO_VALUE; +use crate::native_commands::models::AdminDone; + +/// `None` for a read that found rows: there is nothing done to name. +pub(crate) fn summary_line(done: &AdminDone) -> Option { + let line: String = match done { + AdminDone::Bootstrapped { id, name } => format!("Created admin user {name} ({id})"), + AdminDone::LocationCreated { id, name } => format!("Registered location {name} ({id})"), + AdminDone::PrincipalCreated { id, name } => { + format!("Created person {name} ({id}) with no roles") + } + AdminDone::PasswordSet { id, name } => format!("Set the password of {name} ({id})"), + AdminDone::AdminGranted { id, name } => format!("Made {name} ({id}) an admin"), + AdminDone::TokenIssued { token, location } => format!( + "Issued a location token for {location} ({}), expires {}", + token.identity.token_id, + until(token.identity.expires_at) + ), + AdminDone::TokenRotated { replaced, token } => format!( + "Replaced token {replaced} with {}, expires {}", + token.identity.token_id, + until(token.identity.expires_at) + ), + AdminDone::TokenRevoked { id, revoked: true } => format!("Revoked token {id}"), + AdminDone::TokenRevoked { id, revoked: false } => { + format!("Token {id} was already revoked or doesn't exist; nothing changed") + } + AdminDone::RunQueued { + run_id, + job, + target, + applied: true, + } => { + format!("Queued a run of {job} on target {target} ({run_id})") + } + AdminDone::RunQueued { + run_id, + applied: false, + .. + } + | AdminDone::RerunQueued { + run_id, + applied: false, + .. + } => { + format!("Run {run_id} was already requested; nothing changed") + } + AdminDone::RerunQueued { + run_id, + source, + applied: true, + } => { + format!("Queued a rerun of run {source} ({run_id})") + } + AdminDone::CheckRequested { + request_id, + location, + target, + applied: true, + } => { + format!("Requested a connection check of {location} on target {target} ({request_id})") + } + AdminDone::CheckRequested { + request_id, + applied: false, + .. + } => { + format!("Connection check {request_id} was already requested; nothing changed") + } + AdminDone::WorkRead { + request_id, + record: None, + .. + } => { + format!("No location request {request_id}") + } + AdminDone::WorkRead { + record: Some(_), .. + } => return None, + AdminDone::CancelRequested { + event_id, + run_id, + applied: true, + } => { + format!("Requested cancellation of run {run_id} ({event_id})") + } + AdminDone::CancelRequested { + event_id, + run_id, + applied: false, + } => format!( + "Cancellation of run {run_id} ({event_id}) was already requested; nothing changed" + ), + AdminDone::TriggerChanged { + event_id, + trigger_id, + applied: false, + .. + } => format!( + "The change to trigger {trigger_id} ({event_id}) was already made; nothing changed" + ), + AdminDone::TriggerChanged { + trigger_id, + change, + applied: true, + .. + } => match change { + TriggerChange::Enable => format!("Enabled trigger {trigger_id}"), + TriggerChange::Pause => format!("Paused trigger {trigger_id}"), + TriggerChange::ResetDefault => { + format!("Reset trigger {trigger_id} to its default status") + } + TriggerChange::SetCursor { time } => format!( + "Set the cursor of trigger {trigger_id} to {}", + time.to_rfc3339_opts(SecondsFormat::AutoSi, true) + ), + TriggerChange::ResetCursor => format!("Reset the cursor of trigger {trigger_id}"), + TriggerChange::SkipEvent { event } => { + format!("Skipped event {event} of trigger {trigger_id}") + } + }, + AdminDone::AccountCreated { account, key } => format!( + "Created service account {} ({}) with role {}{}", + account.name, + account.principal_id, + role_text(account.role), + match key { + Some(_) => "; its key is shown only this once", + None => " and the imported key", + } + ), + AdminDone::KeyRotated { account, .. } => rotated(account), + AdminDone::AccountSwitched { account, disabled } => format!( + "{} service account {} ({})", + if *disabled { "Disabled" } else { "Enabled" }, + account.name, + account.principal_id + ), + AdminDone::AccountsListed(accounts) => { + return accounts + .is_empty() + .then(|| "No service accounts".to_owned()); + } + }; + Some(printable(&line)) +} + +fn rotated(account: &ServiceAccountSummary) -> String { + let overlap: String = account + .keys + .get(1) + .and_then(|key| key.expires_at) + .map_or_else( + || "has stopped".to_owned(), + |stops| format!("works until {}", until(stops)), + ); + format!( + "Rotated the key of service account {} ({}); the replaced key {overlap}", + account.name, account.principal_id + ) +} + +fn until(time: DateTime) -> String { + time.format("%Y-%m-%d %H:%M UTC").to_string() +} + +pub(crate) fn role_text(role: Option) -> String { + serde_json::json!(role) + .as_str() + .unwrap_or(NO_VALUE) + .to_owned() +} + +/// A stored label can't add lines or terminal controls. +pub(crate) fn printable(text: &str) -> String { + text.chars() + .map(|letter| { + if letter.is_control() { + letter.escape_default().to_string() + } else { + letter.to_string() + } + }) + .collect() +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/admin_actions.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/admin_actions.rs new file mode 100644 index 0000000000..ee49ab2644 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/admin_actions.rs @@ -0,0 +1,97 @@ +//! Token and service account commands the control-store owner runs; a new key appears only in the result. + +use sqlbuild_orchestration::authorization::main::service_accounts::{ + create_service_account::create_service_account, find_service_account::find_service_account, + list_service_accounts::list_service_accounts, rotate_service_key::rotate_service_key, + set_service_account_disabled::set_service_account_disabled, +}; +use sqlbuild_orchestration::credentials::main::identities::recorded_name::recorded_name; +use sqlbuild_orchestration::credentials::main::tokens::issue_token::issue_token; +use sqlbuild_orchestration::credentials::main::tokens::revoke_token::revoke_token; +use sqlbuild_orchestration::credentials::main::tokens::rotate_token::rotate_token; +use sqlbuild_orchestration::credentials::models::{ + AuditContext, CredentialScope, ServiceAccountAuthority, ServiceKeyRotation, +}; +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; + +use crate::native_commands::models::{AdminDone, ServiceAccountAdmin, TokenAdmin}; +use uuid::Uuid; + +/// A location token command, by the control-store owner. +pub(crate) async fn run_token_admin( + store: &ControlStore, + context: &AuditContext, + action: TokenAdmin, +) -> Result { + let location: String = match &action { + TokenAdmin::Issue(CredentialScope::Location { location_id }, _) => { + name_or_id(store, *location_id).await? + } + _ => String::new(), + }; + match action { + TokenAdmin::Issue(scope, expires_at) => Ok(AdminDone::TokenIssued { + token: issue_token(store, context, scope, expires_at).await?, + location, + }), + TokenAdmin::Revoke(id) => Ok(AdminDone::TokenRevoked { + id, + revoked: revoke_token(store, context, id).await?, + }), + TokenAdmin::Rotate(replaced) => Ok(AdminDone::TokenRotated { + replaced, + token: rotate_token(store, context, replaced).await?, + }), + } +} + +/// A service account command, by the control-store owner. +pub(crate) async fn run_service_account_admin( + store: &ControlStore, + context: &AuditContext, + action: ServiceAccountAdmin, +) -> Result { + let owner = (context, ServiceAccountAuthority::Owner); + match action { + ServiceAccountAdmin::Create { request, key } => { + let issued = create_service_account(store, owner, (&request, key.as_deref())).await?; + Ok(AdminDone::AccountCreated { + account: issued.account, + key: key.is_none().then_some(issued.key), + }) + } + ServiceAccountAdmin::Rotate { + name, + overlap_minutes, + } => { + let principal_id = find_service_account(store, &name).await?; + let rotation = ServiceKeyRotation { + overlap_minutes: Some(overlap_minutes), + }; + let issued = rotate_service_key(store, owner, (principal_id, rotation)).await?; + Ok(AdminDone::KeyRotated { + account: issued.account, + key: issued.key, + }) + } + ServiceAccountAdmin::SetDisabled { name, disabled } => { + let principal_id = find_service_account(store, &name).await?; + Ok(AdminDone::AccountSwitched { + account: set_service_account_disabled(store, owner, (principal_id, disabled)) + .await?, + disabled, + }) + } + ServiceAccountAdmin::List => Ok(AdminDone::AccountsListed( + list_service_accounts(store, owner).await?, + )), + } +} + +/// What `id` names, read before the change so that a failed read can't hide a committed one or its secret. +pub(crate) async fn name_or_id(store: &ControlStore, id: Uuid) -> Result { + Ok(recorded_name(store, id) + .await? + .unwrap_or_else(|| id.to_string())) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs index fcac7c9416..b192b3b710 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs @@ -1,5 +1,10 @@ //! Resolve native invocations and control-service settings from parsed arguments. +use crate::server_config::constants::BYTE_UNITS; +use crate::server_config::models::ByteCount; +use sqlbuild_orchestration::run_output::main::open_output_store::open_output_store; +use sqlbuild_orchestration::run_output::models::{OutputSettings, OutputStore}; +use sqlbuild_orchestration::store::models::ControlStore; use std::net::{IpAddr, SocketAddr}; use std::path::PathBuf; @@ -7,7 +12,9 @@ use chrono::{DateTime, Utc}; use serde_json::json; use sqlbuild_orchestration::acknowledgements::models::AttentionSnooze; use sqlbuild_orchestration::api::models::{ApiAuthentication, HumanLogin, ServerFacts}; -use sqlbuild_orchestration::credentials::models::{AuditRetention, CredentialScope}; +use sqlbuild_orchestration::credentials::models::{ + AuditRetention, BuiltinRole, CredentialScope, NewServiceAccount, +}; use sqlbuild_orchestration::declarations::models::TriggerChange; use sqlbuild_orchestration::platform::models::{LocationWork, LocationWorkRequest}; use sqlbuild_orchestration::runs::models::RunLogRetention; @@ -20,10 +27,11 @@ use sqlbuild_orchestration::warehouse_metadata::models::{ use uuid::Uuid; use crate::argv::constants::{JSON_OPTION, REVIEW_PROG}; -use crate::argv::models::{ArgvOutcome, Namespace, Value}; +use crate::argv::models::{ArgvOutcome, Namespace, Stream, Value}; use crate::dispatch::main::invocation_policy::invocation_policy; use crate::dispatch::models::{CommandFacts, InvocationPolicy}; use crate::native_commands::_helpers::command::terminal::read_password; +use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::constants::{ CLEAN_COMMAND, INIT_COMMAND, RULES_COMMAND, RULES_LIST_ACTION, RULES_SHOW_ACTION, SKILLS_COMMAND, @@ -31,7 +39,7 @@ use crate::native_commands::constants::{ use crate::native_commands::errors::PythonNeeded; use crate::native_commands::models::{ ControlAdmin, CostOptions, NativeCommand, NativeInvocation, RulesAction, RulesOptions, - SkillsOptions, + ServiceAccountAdmin, SkillsOptions, TokenAdmin, }; use crate::server_config::models::{ServerConfig, ServerSection}; use sqlbuild_core::cost_command::constants::DESCENDING_ORDER; @@ -71,6 +79,9 @@ pub(crate) fn control_admin(namespace: &Namespace) -> Result Result Ok(ControlAdmin::RevokeToken(id)), - Some("rotate-token") => Ok(ControlAdmin::RotateToken(id)), + Some("revoke-token") => Ok(ControlAdmin::Token(TokenAdmin::Revoke(id))), + Some("rotate-token") => Ok(ControlAdmin::Token(TokenAdmin::Rotate(id))), Some("set-password") => Ok(ControlAdmin::SetPassword(id, read_password()?)), Some("grant-admin") => Ok(ControlAdmin::GrantAdmin(id)), _ => Err(ControlError::Invalid( @@ -342,6 +353,7 @@ pub(crate) fn control_api_settings( origin, version: env!("CARGO_PKG_VERSION").into(), scheduler: scheduler_enabled(namespace, standalone, &config.server), + output: None, audit, statistics, snapshots, @@ -451,8 +463,77 @@ pub(crate) fn control_database( } } +/// The service account command `action` names, or none for the other admin commands. +fn service_account_admin( + namespace: &Namespace, + action: Option<&str>, + name: &str, +) -> Result, ControlError> { + let named = || { + if name.trim().is_empty() { + Err(ControlError::Invalid( + "service account name is required".into(), + )) + } else { + Ok(name.trim().to_owned()) + } + }; + let admin = match action { + Some("create-service-account") => ServiceAccountAdmin::Create { + request: NewServiceAccount { + name: named()?, + description: text(namespace, "admin_description"), + role: service_role(namespace)?, + }, + key: imported_key(namespace)?, + }, + Some("rotate-service-account") => ServiceAccountAdmin::Rotate { + name: named()?, + overlap_minutes: match namespace.get("admin_overlap_minutes") { + Some(Value::Int(minutes)) => minutes.parse::().map_err(|_| { + ControlError::Invalid("--overlap-minutes must be a whole number".into()) + })?, + _ => 0, + }, + }, + Some("disable-service-account") => ServiceAccountAdmin::SetDisabled { + name: named()?, + disabled: true, + }, + Some("enable-service-account") => ServiceAccountAdmin::SetDisabled { + name: named()?, + disabled: false, + }, + Some("list-service-accounts") => ServiceAccountAdmin::List, + _ => return Ok(None), + }; + Ok(Some(ControlAdmin::ServiceAccount(admin))) +} + +/// The built-in role `--role` names. +fn service_role(namespace: &Namespace) -> Result { + serde_json::from_value(json!(text(namespace, "admin_role").unwrap_or_default())) + .map_err(|_| ControlError::Invalid("--role is viewer, operator, developer or admin".into())) +} + +/// The key held in the variable `--key-from-env` names, when it names one. +fn imported_key(namespace: &Namespace) -> Result, ControlError> { + let Some(variable) = text(namespace, "admin_key_env") else { + return Ok(None); + }; + match std::env::var(&variable) { + Ok(key) if !key.is_empty() => Ok(Some(key)), + Ok(_) | Err(std::env::VarError::NotPresent) => Err(ControlError::Invalid(format!( + "--key-from-env names {variable}, which is not set" + ))), + Err(std::env::VarError::NotUnicode(_)) => Err(ControlError::Invalid(format!( + "--key-from-env names {variable}, which doesn't hold UTF-8 text" + ))), + } +} + /// The strings of a list attribute, or `None` when it holds anything else. -fn texts(namespace: &Namespace, name: &str) -> Option> { +pub(crate) fn texts(namespace: &Namespace, name: &str) -> Option> { match namespace.get(name) { None | Some(Value::None) => Some(Vec::new()), Some(Value::List(items)) => items @@ -534,3 +615,68 @@ pub(crate) fn native_invocation(namespace: &Namespace) -> Result Result, ControlError> { + let output = open_output_store(&control_output_settings(config)?, store)?; + drop(write_output(&[( + Stream::Stderr, + &format!("Run output store: {}\n", output.location()), + )])); + facts.output = Some(output.clone()); + Ok(Some(( + output, + run_output_days(namespace, config, facts.run_logs)?, + ))) +} + +/// `[output]`: the output store's URL and the bytes kept per run. +fn control_output_settings(config: &ServerConfig) -> Result { + Ok(OutputSettings { + store: config.output.store.clone(), + max_bytes_per_run: match &config.output.max_bytes_per_run { + Some(ByteCount::Number(bytes)) => Some(*bytes), + Some(ByteCount::Text(text)) => Some(byte_count(text)?), + None => None, + }, + }) +} + +/// Days a finished run's output stays, `--run-output-retention-days` over `[retention] run_output_days`, by default `run_log_days`. +fn run_output_days( + namespace: &Namespace, + config: &ServerConfig, + run_logs: RunLogRetention, +) -> Result { + Ok(retention_setting( + namespace, + "run-output-retention-days", + ("run_output_days", config.retention.run_output_days), + )? + .unwrap_or(run_logs.days())) +} + +/// `20GB`, `500 MB` or `2GiB` as bytes; decimal units step by 1000 and binary ones by 1024. +fn byte_count(text: &str) -> Result { + let invalid = || { + ControlError::Invalid(format!( + "[output] max_bytes_per_run must be a number of bytes or text such as \"20GB\", not {text:?}" + )) + }; + let trimmed: &str = text.trim(); + let split: usize = trimmed + .find(|character: char| !character.is_ascii_digit()) + .unwrap_or(trimmed.len()); + let (digits, unit) = trimmed.split_at(split); + let count: u64 = digits.parse().map_err(|_| invalid())?; + let scale: u64 = BYTE_UNITS + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case(unit.trim())) + .map(|(_, scale)| *scale) + .ok_or_else(invalid)?; + count.checked_mul(scale).ok_or_else(invalid) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/mod.rs index 10deaba6b2..db72a5b64e 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod admin_actions; pub(crate) mod argv_host; pub(crate) mod decision; pub(crate) mod init; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs index 685e59187e..298e78e019 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/paths.rs @@ -12,7 +12,7 @@ use sqlbuild_core::git_revisions::main::head_commit::head_commit; use sqlbuild_rules::project_tree::main::project_real_path::project_real_path; use tokio::time::Instant; -use crate::native_commands::constants::LOCATION_COMMIT_CHECK_SECONDS; +use crate::native_commands::constants::{DEVELOPMENT_OUTPUT_FOLDER, LOCATION_COMMIT_CHECK_SECONDS}; use crate::native_commands::errors::PythonNeeded; use crate::native_commands::models::{LocationWatch, ProjectLocation}; use crate::replay::main::output_file_identities::output_file_identities; @@ -25,18 +25,22 @@ pub(crate) fn location_watch(root: &Path) -> LocationWatch { .map(|path| path.to_string_lossy().into_owned()) .collect(); let local_files = location_database_files(root, files); + let output: Option = std::env::var_os(DEVELOPMENT_OUTPUT_FOLDER).map(PathBuf::from); + let output_folders: Vec = location_output_folders(root, output.as_deref()); LocationWatch { observed: ( - location_files(root, &rules, &local_files), + location_files(root, &rules, (&local_files, &output_folders)), head_commit(root), ), rules, local_files, + output_folders, attempted: None, changed_at: tokio::time::Instant::now(), retry_at: None, commit_checked_at: tokio::time::Instant::now(), checked: false, + republish: None, } } @@ -54,7 +58,11 @@ pub(crate) fn observe_location_inputs( watch.observed.1.clone() }; let current = ( - location_files(root, &watch.rules, &watch.local_files), + location_files( + root, + &watch.rules, + (&watch.local_files, &watch.output_folders), + ), commit, ); if watch.observed != current { @@ -95,7 +103,7 @@ fn location_rules() -> SnapshotRules { pub(crate) fn location_files( root: &Path, rules: &SnapshotRules, - local_files: &[PathBuf], + (local_files, output_folders): (&[PathBuf], &[PathBuf]), ) -> Vec { let mut stamps = snapshot_project_files(root, rules); stamps.retain(|stamp| { @@ -105,6 +113,10 @@ pub(crate) fn location_files( .any(|suffix| stamp.relative_path.ends_with(suffix)) }); stamps = exclude_location_files(stamps, root, local_files); + stamps.retain(|stamp| { + let path: PathBuf = root.join(&stamp.relative_path); + !output_folders.iter().any(|folder| path.starts_with(folder)) + }); #[cfg(windows)] { let output: Vec = @@ -171,6 +183,27 @@ pub(crate) fn location_database_files(root: &Path, files: Vec) -> Vec) -> Vec { + let Some(folder) = folder else { + return Vec::new(); + }; + let authored: PathBuf = pathlib_path(&root.join(folder)); + let resolved: PathBuf = resolved_path(&authored, root); + let real_root: PathBuf = project_real_path(root); + if real_root.starts_with(&resolved) { + return Vec::new(); + } + [ + authored.strip_prefix(root), + resolved.strip_prefix(&real_root), + ] + .into_iter() + .flatten() + .map(|inside| root.join(inside)) + .collect() +} + /// `Path(text)`: repeated separators, `.` parts and trailing separators dropped. pub(crate) fn pathlib_path(text: &Path) -> PathBuf { let path: PathBuf = text diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/store_migration.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/store_migration.rs index 8a3aca6588..0aada290dd 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/store_migration.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/store_migration.rs @@ -11,14 +11,12 @@ use crate::native_commands::_helpers::command::decision::{ control_database, control_database_variable, flag, }; use crate::native_commands::_helpers::command::terminal::{finish_lost_stdout, write_output}; +use crate::native_commands::constants::OPENING_STORE; use crate::server_config::main::read_server_config::read_server_config; /// Run `sqb server migrate` on `runtime` and return its exit code. pub(crate) fn run_store_migration(namespace: &Namespace, runtime: &tokio::runtime::Runtime) -> i32 { - drop(write_output(&[( - Stream::Stderr, - "Opening control store...\n", - )])); + drop(write_output(&[(Stream::Stderr, OPENING_STORE)])); match runtime.block_on(store_migration( namespace, flag(namespace, "control_dry_run"), diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_start.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_start.rs new file mode 100644 index 0000000000..bb2968feae --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_start.rs @@ -0,0 +1,68 @@ +//! Start the control API and the platform roles that run beside it. + +use std::net::SocketAddr; + +use sqlbuild_orchestration::api::main::serve_api::serve_api; +use sqlbuild_orchestration::api::models::{ApiAuthentication, ServerFacts}; +use sqlbuild_orchestration::platform::models::RetentionPolicies; +use sqlbuild_orchestration::run_output::models::OutputStore; +use sqlbuild_orchestration::runs::types::RunHandoff; +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; +use tokio::sync::watch; +use tokio::task::JoinSet; + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::execution::start_platform_roles; + +/// Resolve once `shutdown` turns true or its sender is gone. +async fn stopped(mut shutdown: watch::Receiver) { + while !*shutdown.borrow_and_update() { + if shutdown.changed().await.is_err() { + break; + } + } +} + +/// Start the control API and the platform roles beside it, with the retention `facts` and `run_output` set. +pub(crate) async fn start_api( + mut tasks: JoinSet>, + (address, store, shutdown): (SocketAddr, &ControlStore, &watch::Receiver), + (authentication, handoff, facts): (ApiAuthentication, RunHandoff, &ServerFacts), + run_output: Option<(OutputStore, u16)>, +) -> Result>, ControlError> { + drop(write_output(&[( + Stream::Stderr, + "Starting control API...\n", + )])); + let listener = tokio::net::TcpListener::bind(address).await?; + let address = listener.local_addr()?; + tasks.spawn(serve_api( + store.clone(), + listener, + (authentication, handoff, facts.clone()), + ( + move || { + drop(write_output(&[( + Stream::Stderr, + &format!("Control API ready: {address}\n"), + )])); + }, + stopped(shutdown.clone()), + ), + )); + start_platform_roles( + &mut tasks, + (store, shutdown), + RetentionPolicies { + audit: facts.audit, + statistics: facts.statistics, + snapshots: facts.snapshots, + run_logs: facts.run_logs, + state_history: facts.state_history, + run_output, + }, + )?; + Ok(tasks) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_discovery.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_discovery.rs new file mode 100644 index 0000000000..9b9fd56ee2 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_discovery.rs @@ -0,0 +1,154 @@ +//! The compiler task's discovered sets: `check_every` checks, and what a publication reports of them. + +use sqlbuild_orchestration::dev_events::main::dev_event_line::dev_event_line; +use sqlbuild_orchestration::dev_events::models::DevEvent; +use sqlbuild_orchestration::discovered_sets::main::discovery_health::discovery_health; +use sqlbuild_orchestration::discovered_sets::main::discovery_summary::discovery_summary; +use sqlbuild_orchestration::discovered_sets::models::{ + DiscoveredSetCheck, DiscoveredSetChecked, DiscoveredSetStatus, +}; +use sqlbuild_orchestration::platform::models::LocationHealth; +use sqlbuild_orchestration::store::errors::ControlError; +use tokio::sync::mpsc; +use tokio::time::Instant; +use uuid::Uuid; + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::discovery_state::LocationDiscovery; +use crate::native_commands::_helpers::location::execution::{ + exchange_reply, report_location_health, request_republish, stop_location_runtime, +}; +use crate::native_commands::models::{ + LocationCompiler, LocationLoad, LocationRuntimeRequest, LocationServe, +}; +use crate::native_commands::types::DiscoveryControls; + +/// How often a running check looks for shutdown or a waiting request. +const REQUEST_POLL: std::time::Duration = std::time::Duration::from_millis(100); +/// How long a running check may go on once a request waits for the interpreter it holds. +const CHECK_GRACE: std::time::Duration = std::time::Duration::from_secs(10); + +/// Wait until every sender of `requests` is gone, which only shutdown does, without taking a request. +async fn shut_down(requests: &mpsc::Receiver) { + while !requests.is_closed() { + tokio::time::sleep(REQUEST_POLL).await; + } +} + +/// Wait until a request has waited out the grace of the check, without taking the request. +async fn waited_out(requests: &mpsc::Receiver) { + while requests.is_empty() { + tokio::time::sleep(REQUEST_POLL).await; + } + tokio::time::sleep(CHECK_GRACE).await; +} + +/// Wait until `due`, or forever without one. +pub(crate) async fn sleep_until(due: Option) { + match due { + Some(due) => tokio::time::sleep_until(due).await, + None => std::future::pending().await, + } +} + +/// Call the set due for its `check_every` again; republish when its result changed. Shutdown, or a request waiting out its grace, stops it. +pub(crate) async fn check_discovered( + compiler: Option, + discovery: &mut LocationDiscovery, + ((republish, _), requests): ( + DiscoveryControls<'_>, + &mpsc::Receiver, + ), +) -> Result, ControlError> { + let (Some(mut active), Some(check)) = (compiler, discovery.due_check(Instant::now())) else { + return Ok(None); + }; + let request: DiscoveredSetCheck = check; + let name: String = request.check_discovered.clone(); + let exchanged: Option>> = tokio::select! { + biased; + reply = exchange_reply(&mut active, &request, "discovered set check") => Some(Some(reply)), + () = shut_down(requests) => None, + () = waited_out(requests) => Some(None), + }; + let Some(reply) = exchanged else { + drop(write_output(&[( + Stream::Stderr, + &format!("Stopped checking discovered set {name}; the location is shutting down.\n"), + )])); + stop_location_runtime(Some(active)).await?; + return Ok(None); + }; + let reply: DiscoveredSetChecked = match reply { + Some(Ok(reply)) => reply, + unfinished => { + let problem: String = match unfinished { + Some(_) => format!("Checking discovered set {name} failed"), + None => format!( + "Checking discovered set {name} did not finish within {} seconds of a request waiting for it", + CHECK_GRACE.as_secs() + ), + }; + drop(write_output(&[( + Stream::Stderr, + &format!("{problem}; the location restarts its interpreter.\n"), + )])); + discovery.checked( + &name, + DiscoveredSetChecked { + set: None, + changed: false, + }, + Instant::now(), + ); + stop_location_runtime(Some(active)).await?; + return Ok(None); + } + }; + if let Some(set) = reply + .set + .as_ref() + .filter(|set| set.status == DiscoveredSetStatus::Failed) + { + drop(write_output(&[( + Stream::Stderr, + &format!( + "Discovered set {name} check failed: {}\n", + set.error.as_deref().unwrap_or("no reason given") + ), + )])); + } + if discovery.checked(&name, reply, Instant::now()) { + drop(write_output(&[( + Stream::Stderr, + &format!("Discovered set {name} changed; publishing it.\n"), + )])); + request_republish(republish, false); + } + Ok(Some(active)) +} + +/// Report a publication's sets as health, and to `sqb dev` as its ready card's line. +pub(crate) async fn discovered( + options: &LocationServe, + (bearer, session_id): (&str, Uuid), + (generation, load, discovery): (i64, &LocationLoad, &LocationDiscovery), +) { + if !discovery.reports(load) { + return; + } + if options.dev_events + && let Some(summary) = discovery_summary(&load.discovered) + { + drop(write_output(&[( + Stream::Stdout, + &dev_event_line(&DevEvent::Discovered { summary }), + )])); + } + let health = LocationHealth::Discovery { + generation, + sets: discovery_health(&load.discovered), + }; + report_location_health(options, bearer, session_id, health).await; +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_restart.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_restart.rs new file mode 100644 index 0000000000..027f49ff93 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/compiler_restart.rs @@ -0,0 +1,41 @@ +//! The compiler task's interpreter restarts when what it loaded at start-up changed. + +use sqlbuild_cache::project_snapshot::models::PathStamp; +use sqlbuild_orchestration::dev_events::main::dev_event_line::dev_event_line; +use sqlbuild_orchestration::dev_events::models::DevEvent; +use sqlbuild_orchestration::store::errors::ControlError; + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::env_reload::reload_env_file; +use crate::native_commands::_helpers::location::execution::stop_location_runtime; +use crate::native_commands::models::{LocationCompiler, LocationServe}; + +/// `compiler`, or none once it was stopped because Python or, under `sqb dev`, the env file changed. +pub(crate) async fn restarted_for_changes( + options: &LocationServe, + mut compiler: Option, + python_sources: &[PathStamp], +) -> Result, ControlError> { + let env_changed: bool = reload_env_file(options); + let python_changed: bool = compiler + .as_ref() + .is_some_and(|compiler| compiler.python_sources != python_sources); + if compiler.is_some() && (python_changed || env_changed) { + stop_location_runtime(compiler.take()).await?; + if options.dev_events { + let reason: &str = if python_changed { + "Python changed" + } else { + "env file changed" + }; + drop(write_output(&[( + Stream::Stdout, + &dev_event_line(&DevEvent::Restarted { + reason: reason.into(), + }), + )])); + } + } + Ok(compiler) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_exposure.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_exposure.rs new file mode 100644 index 0000000000..18ad2629ff --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_exposure.rs @@ -0,0 +1,89 @@ +//! Where `sqb dev` listens, the names it also takes, and whom that opens it to. + +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + +use sqlbuild_orchestration::api::models::DevelopmentScope; +use sqlbuild_orchestration::store::errors::ControlError; + +use crate::argv::models::Namespace; +use crate::native_commands::_helpers::command::decision::{control_address, text, texts}; +use crate::server_config::models::ServerSection; + +/// The address `sqb dev` listens on: loopback, unless `--host` says otherwise. +pub(crate) fn development_address(namespace: &Namespace) -> Result { + control_address(namespace, false, &ServerSection::default())? + .ok_or_else(|| ControlError::Invalid("development address is required".into())) +} + +/// Only an explicit `--host` lets the sign-in-free API leave loopback. +pub(crate) fn listens_beyond_loopback(namespace: &Namespace) -> bool { + text(namespace, "control_host").is_some() +} + +/// The `--allow-host` names in lower case, IPv6 addresses in brackets. +pub(crate) fn allowed_hosts(namespace: &Namespace) -> Result, ControlError> { + texts(namespace, "development_allow_host") + .unwrap_or_default() + .iter() + .map(|value| allowed_host(value)) + .collect() +} + +/// One `--allow-host` value as `name` or `name:port`. +fn allowed_host(value: &str) -> Result { + let refused = || { + ControlError::Invalid(format!( + "--allow-host {value:?} must be a name or IP address, optionally with :port, without \ + a scheme, path or wildcard" + )) + }; + let entry: String = value.to_ascii_lowercase(); + if let Ok(ip) = entry.parse::() { + return Ok(format!("[{ip}]")); + } + let (name, port): (&str, Option<&str>) = match entry.rsplit_once(':') { + Some((name, port)) if !port.ends_with(']') => (name, Some(port)), + _ => (&entry, None), + }; + if let Some(port) = port { + let _: std::num::NonZeroU16 = port.parse().map_err(|_| refused())?; + } + if let Some(address) = name + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + { + let _: Ipv6Addr = address.parse().map_err(|_| refused())?; + } else if name.is_empty() + || !name + .chars() + .all(|letter| letter.is_ascii_alphanumeric() || "-._".contains(letter)) + { + return Err(refused()); + } + Ok(entry) +} + +/// An address this machine can connect to: loopback when listening on every interface. +pub(crate) fn connect_address(address: SocketAddr) -> SocketAddr { + let ip: IpAddr = match address.ip() { + IpAddr::V4(ip) if ip.is_unspecified() => Ipv4Addr::LOCALHOST.into(), + IpAddr::V6(ip) if ip.is_unspecified() => Ipv6Addr::LOCALHOST.into(), + ip => ip, + }; + SocketAddr::new(ip, address.port()) +} + +/// Who gets in without signing in; `None` for a loopback-only session. +pub(crate) fn exposure(address: SocketAddr, scope: &DevelopmentScope) -> Option { + let listener: Option = (!address.ip().is_loopback()).then(|| address.to_string()); + let reached: Vec = listener + .into_iter() + .chain(scope.allowed_hosts.iter().cloned()) + .collect(); + (!reached.is_empty()).then(|| { + format!( + "anyone who can reach {} has full, sign-in-free access with your credentials", + reached.join(" or ") + ) + }) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_start.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_start.rs index ab0924cbc1..18b361b31d 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_start.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_start.rs @@ -19,8 +19,11 @@ use crate::dev_stop::main::stop_switch::stop_switch; use crate::dev_stop::models::{DevEnd, StopReason}; use crate::native_commands::_helpers::command::decision::flag; use crate::native_commands::_helpers::command::project_facts::development_config; +use crate::native_commands::_helpers::location::dev_exposure::{ + allowed_hosts, development_address, +}; use crate::native_commands::_helpers::location::execution::{ - announced_store, loopback_address, run_development_roles, + announced_store, run_development_roles, }; /// Open the store and the port, each a step that can fail, then run every role; a stop before then ends it cleanly. @@ -82,13 +85,15 @@ async fn open_services( next: Vec::new(), } }; - let address: SocketAddr = match loopback_address(namespace) { + let checked: Result = + allowed_hosts(namespace).and_then(|_| development_address(namespace)); + let address: SocketAddr = match checked { Ok(address) => address, Err(error) => { return Err(not_started( DevStep::Api, "UI server address", - (message(error), "pass --port with a free port on 127.0.0.1"), + (message(error), "check --host, --port and --allow-host"), )); } }; @@ -123,7 +128,7 @@ async fn open_services( "UI server", ( format!("could not listen on {address}: {error}"), - "stop whatever uses the port, or pick another with --port (0 picks a free one)", + "stop whatever uses the port, or pick another with --port (0 picks a free one); a --host must be an address of this machine", ), )); } diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/discovery_state.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/discovery_state.rs new file mode 100644 index 0000000000..c275ff63c4 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/discovery_state.rs @@ -0,0 +1,156 @@ +//! What a location's compiler task keeps of its discovered sets between publications. + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Duration; + +use sqlbuild_cache::project_snapshot::models::PathStamp; +use sqlbuild_orchestration::discovered_sets::models::{ + DiscoveredSetCheck, DiscoveredSetChecked, DiscoveryPublishRequest, +}; +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; +use tokio::time::Instant; + +use crate::native_commands::models::LocationLoad; + +/// The sets the location last published, where their functions live, and when each is next checked. +#[derive(Debug, Default)] +pub(crate) struct LocationDiscovery { + sets: DiscoveredSets, + files: BTreeMap, + /// Each set's next `check_every` check. + due: BTreeMap, + /// Whether this location has published since it started; its first publication discovers everything. + published: bool, + /// The `rediscovers` count the last publication satisfied. + rediscovers: u64, + /// The `rediscovers` count the newest request asked for. + requested: u64, + /// The functions edited since the last publication. + edited: BTreeSet, +} + +impl LocationDiscovery { + /// The request for `generation`: everything first or on request, else only edited functions. + pub(crate) fn publish_request( + &mut self, + generation: i64, + (before, after): (&[PathStamp], &[PathStamp]), + rediscovers: u64, + ) -> DiscoveryPublishRequest { + let everything: bool = !self.published || rediscovers != self.rediscovers; + self.requested = rediscovers; + let changed: BTreeSet<&str> = changed_paths(before, after); + for (name, file) in &self.files { + if changed.contains(file.as_str()) { + self.edited.insert(name.clone()); + } + } + let rediscover: Option> = (!everything).then(|| self.edited.clone()); + DiscoveryPublishRequest { + generation, + rediscover, + previous: self.sets.clone(), + seed: !self.published, + } + } + + /// Keep what a publication's compile used, and schedule each set's next check from `now`. + pub(crate) fn published(&mut self, load: &LocationLoad, now: Instant) { + if load.published.is_some() { + self.published = true; + self.rediscovers = self.requested; + self.edited.clear(); + self.files.clone_from(&load.discover_files); + } + if load.discovered.is_empty() && load.published.is_none() { + return; + } + let mut refetched: BTreeSet = BTreeSet::new(); + for (name, set) in &load.discovered { + let before = self.sets.get(name).map(|before| before.fetched_at); + if before != Some(set.fetched_at) { + refetched.insert(name.clone()); + } + } + self.sets.clone_from(&load.discovered); + let mut due: BTreeMap = BTreeMap::new(); + for (name, set) in &self.sets { + let Some(seconds) = set.check_every_seconds else { + continue; + }; + let next: Instant = match self.due.get(name) { + Some(next) if !refetched.contains(name) => *next, + _ => now + Duration::from_secs(seconds), + }; + due.insert(name.clone(), next); + } + self.due = due; + } + + /// Whether to report `load`'s sets: on the first publication, with sets, or when the last one went. + pub(crate) fn reports(&self, load: &LocationLoad) -> bool { + load.published.is_some() + && (!self.published || !load.discovered.is_empty() || !self.sets.is_empty()) + } + + /// When the next check is due; `None` when no set is checked. + pub(crate) fn next_due(&self) -> Option { + self.due.values().min().copied() + } + + /// The check of the set due soonest, if it is due at `now`. + pub(crate) fn due_check(&self, now: Instant) -> Option { + let (name, _) = self + .due + .iter() + .filter(|(_, at)| **at <= now) + .min_by_key(|(_, at)| **at)?; + Some(DiscoveredSetCheck { + check_discovered: name.clone(), + previous: self.sets.get(name).cloned(), + }) + } + + /// Keep a changed result for the next publication; true when the location should republish. + pub(crate) fn checked( + &mut self, + name: &str, + reply: DiscoveredSetChecked, + now: Instant, + ) -> bool { + let every: Option = self.sets.get(name).and_then(|set| set.check_every_seconds); + match every { + Some(seconds) => { + self.due + .insert(name.to_owned(), now + Duration::from_secs(seconds)); + } + None => { + self.due.remove(name); + } + } + match reply.set { + Some(set) if reply.changed => { + self.sets.insert(name.to_owned(), set); + true + } + _ => false, + } + } +} + +/// The relative paths whose stamps differ between `before` and `after`, added and removed ones too. +fn changed_paths<'a>(before: &'a [PathStamp], after: &'a [PathStamp]) -> BTreeSet<&'a str> { + let index = |stamps: &'a [PathStamp]| -> BTreeMap<&'a str, &'a PathStamp> { + stamps + .iter() + .map(|stamp| (stamp.relative_path.as_str(), stamp)) + .collect() + }; + let (before, after) = (index(before), index(after)); + before + .keys() + .chain(after.keys()) + .copied() + .filter(|path| before.get(path) != after.get(path)) + .collect() +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/env_reload.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/env_reload.rs index 960a383530..0902167910 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/env_reload.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/env_reload.rs @@ -37,9 +37,7 @@ pub(crate) fn reload_env_file(options: &LocationServe) -> bool { match load_env_file(&options.project_dir, Some(&options.target)) { Ok(Some(load)) => { let changed: bool = changes_values(&load.overlay); - if changed { - install_environment_overlay(load.overlay); - } + install_environment_overlay(load.overlay); changed } Ok(None) => false, diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs index 1eae0370af..baa19bb055 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs @@ -17,7 +17,7 @@ use crate::dev_session::models::{DevProject, LocationPipes}; use crate::dev_stop::main::stop_switch::stop_switch; use crate::dev_stop::models::DevEnd; use crate::native_commands::_helpers::command::decision::{ - control_address, control_database, control_database_variable, flag, text, + control_database, control_database_variable, flag, text, }; use crate::native_commands::_helpers::command::init::run_init; use crate::native_commands::_helpers::command::package::installed_package; @@ -35,16 +35,19 @@ use crate::native_commands::_helpers::command::terminal::{ }; use crate::native_commands::_helpers::command::terminal::{live_screen, screen_colour}; use crate::native_commands::_helpers::location::dev_cancel::DevRuns; +use crate::native_commands::_helpers::location::dev_exposure::{ + allowed_hosts, connect_address, exposure, listens_beyond_loopback, +}; use crate::native_commands::_helpers::location::dev_supervision::{ DevRoles, supervise_development_roles, }; use crate::native_commands::_helpers::location::dynamic_resume::resume_expired_holds; use crate::native_commands::_helpers::location::env_reload::env_file_summary; use crate::native_commands::_helpers::location::provider_secrets::report_provider_secrets; +use crate::native_commands::_helpers::location::republish::settle_republish; use crate::native_commands::_helpers::location::sync_report::{ metadata_health, read_timeout_seconds, rows_text, scan_line, }; -use crate::native_commands::constants::PLAN_NOT_PRODUCED; use crate::native_commands::constants::{ ADMIN_COMMAND, CHANGED_PATHS_SHOWN, COLUMNS_VARIABLE, FALLBACK_COLUMNS, FALLBACK_ROWS, METADATA_OVERLAP_SECONDS, METADATA_POLL_SECONDS, METADATA_READER_CLOSE_SECONDS, @@ -52,15 +55,19 @@ use crate::native_commands::constants::{ METADATA_SYNC_CHECK_SECONDS, SAFETY_SYNC_ENV, SCHEDULER_COMMAND, UNCAUGHT_EXCEPTION_STATUS, UNKNOWN_COMMAND, }; +use crate::native_commands::constants::{DEVELOPMENT_OUTPUT_FOLDER, PLAN_NOT_PRODUCED}; +use crate::native_commands::constants::{OPENING_STORE, STORE_READY}; use crate::native_commands::errors::PythonNeeded; use crate::native_commands::main::_run_admin::run_admin; use crate::native_commands::main::_run_control::run_control; use crate::native_commands::main::_run_cost::run_cost; +use crate::native_commands::models::AdminDone; use crate::native_commands::models::{ CommandOutput, DevControlState, InstalledPackage, LocationCompileRequest, LocationCompiler, LocationMetadataPage, LocationMetadataSync, LocationServe, LocationWatch, LostStdout, MetadataReply, NativeCommand, NativeInvocation, ProjectLocation, ScanToken, }; +use crate::native_commands::models::{LoadedGeneration, PendingRepublish}; use crate::native_commands::models::{ LocationLoad, LocationRuntimeRequest, ReadFailure, SyncProgress, }; @@ -111,6 +118,8 @@ use sqlbuild_orchestration::platform::models::{ LocationHealth, LocationHealthReport, LocationWorkClient, LocationWorkPoll, RetentionPolicies, WarehouseSyncFailure, }; +use sqlbuild_orchestration::run_output::main::open_output_store::open_output_store; +use sqlbuild_orchestration::run_output::models::{OutputSettings, OutputStore}; use sqlbuild_orchestration::runs::types::RunHandoff; use sqlbuild_orchestration::scheduler::main::run_scheduler::run_scheduler; use sqlbuild_orchestration::scheduler::models::SchedulerState; @@ -135,7 +144,6 @@ use sqlbuild_orchestration::webhooks::models::{Webhook, WebhookSource}; use std::collections::{BTreeMap, HashMap}; use std::future::Future; use std::io; -use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::{Duration, SystemTime}; @@ -154,8 +162,10 @@ pub(crate) async fn run_development_roles( listener: tokio::net::TcpListener, (scheduler, (messages, actions, keys)): (bool, DevScreenParts), ) -> Result { - let address = listener.local_addr()?; + let listening = listener.local_addr()?; + let address = connect_address(listening); let url = format!("http://{address}"); + let opened_to: Option = exposure(listening, &scope); let location_id = scope.location_id; let target = scope.target.clone(); let workers = open_development_workers( @@ -171,6 +181,7 @@ pub(crate) async fn run_development_roles( detail: String::new(), })); let api_ready = messages.clone(); + let output: OutputStore = open_output_store(&OutputSettings::default(), &store)?; roles.spawn( Some("UI server"), serve_api( @@ -185,6 +196,7 @@ pub(crate) async fn run_development_roles( ServerFacts { version: env!("CARGO_PKG_VERSION").into(), scheduler, + output: Some(output.clone()), ..ServerFacts::default() }, ), @@ -194,6 +206,9 @@ pub(crate) async fn run_development_roles( step: DevStep::Api, detail: address.to_string(), })); + if let Some(opened_to) = opened_to { + drop(api_ready.send(ScreenMessage::Exposed(opened_to))); + } }, development_stopped(shutdown.clone()), ), @@ -203,7 +218,7 @@ pub(crate) async fn run_development_roles( let (location, pipes) = development_location_role( (&project, &executable), (location_id, &target), - (&url, &store), + (&url, &store, output.local_folder()), shutdown.clone(), )?; roles.spawn(Some("code location"), location); @@ -267,11 +282,11 @@ async fn development_stopped(mut shutdown: watch::Receiver) { } } -/// Hand off only the local file exclusion, never control-store connection credentials. +/// Hand off only the local file and output folder exclusions, never control-store connection credentials. fn development_location_role( (project, executable): (&Path, &Path), (location_id, target): (Uuid, &str), - (url, store): (&str, &ControlStore), + (url, store, output): (&str, &ControlStore, Option<&Path>), shutdown: watch::Receiver, ) -> Result< ( @@ -301,6 +316,7 @@ fn development_location_role( .env_remove(SECURITY_AUDIT_WEBHOOK_VARIABLE) .env_remove(RUN_TOKEN_VARIABLE) .env_remove("SQLBUILD_DEVELOPMENT_CONTROL_FILE") + .env_remove(DEVELOPMENT_OUTPUT_FOLDER) .env(DEV_EVENTS_VARIABLE, DEV_EVENTS_ON) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -314,6 +330,9 @@ fn development_location_role( std::env::current_dir()?.join(path), ); } + if let Some(folder) = output { + command.env(DEVELOPMENT_OUTPUT_FOLDER, folder); + } let mut child = command.spawn()?; let group: Option = child.id(); if let Some(group) = group { @@ -391,10 +410,13 @@ pub(crate) async fn compile_generation( "Location compiler failed; generation {generation} may already be published: {error}\n" ), )])); - dev_failure(dev_events, generation, error); + dev_failure(dev_events, generation, error.clone()); LocationLoad { published: None, rules: None, + discovered: Default::default(), + discover_files: Default::default(), + error: Some(error), } } }; @@ -403,12 +425,17 @@ pub(crate) async fn compile_generation( refresh_at: refresh, state_locations: locations, missing_secrets, + secrets_needed_by, }) = load.published else { - if let Some(rules) = &load.rules { - dev_failure(dev_events, generation, rule_failure_text(rules)); + let rules_text: Option = load.rules.as_ref().map(rule_failure_text); + if let Some(text) = &rules_text { + dev_failure(dev_events, generation, text.clone()); } - return Ok(Some(Err(load.rules))); + let error: String = rules_text.or(load.error).unwrap_or_else(|| { + "the compile failed; the location's output has the error".to_owned() + }); + return Ok(Some(Err((load.rules, error)))); }; let refresh_at = refresh .map(|deadline| Instant::now() + (deadline - Utc::now()).to_std().unwrap_or_default()); @@ -431,7 +458,12 @@ pub(crate) async fn compile_generation( record.snapshot_id ))); } - Ok(Some(Ok((refresh_at, locations, missing_secrets)))) + Ok(Some(Ok(LoadedGeneration { + refresh_at, + state_locations: locations, + secrets: (missing_secrets, secrets_needed_by), + snapshot_id: record.snapshot_id, + }))) } /// Under `sqb dev`, tell the screen a generation failed; the last good generation keeps serving. @@ -463,15 +495,15 @@ fn rule_failure_text(rules: &LocationRuleFailure) -> String { ) } -/// The child is retained by its owning task while this exchange can be cancelled. -pub(crate) async fn exchange_location_generation( +/// Send `request` as a JSON line and read the runtime's reply, a `what`; `sqb dev` events pass on. +pub(crate) async fn exchange_reply( compiler: &mut LocationCompiler, - generation: i64, -) -> Result { - compiler - .stdin - .write_all(format!("{generation}\n").as_bytes()) - .await?; + request: &impl serde::Serialize, + what: &str, +) -> Result { + let mut line: Vec = serde_json::to_vec(request).map_err(std::io::Error::other)?; + line.push(b'\n'); + compiler.stdin.write_all(&line).await?; compiler.stdin.flush().await?; let mut line = String::new(); loop { @@ -482,13 +514,12 @@ pub(crate) async fn exchange_location_generation( )); } if parse_dev_event(&line).is_none() { - break; + return serde_json::from_str(&line).map_err(|_| { + ControlError::Invalid(format!("location interpreter returned an invalid {what}")) + }); } drop(write_output(&[(Stream::Stdout, &line)])); } - serde_json::from_str(&line).map_err(|_| { - ControlError::Invalid("location interpreter returned an invalid publication record".into()) - }) } /// The caller retains and reaps the child while a cancellable bounded exchange owns its pipes. @@ -1175,7 +1206,7 @@ pub(crate) fn start_platform_roles( pub(crate) async fn run_control_action( namespace: &Namespace, command: &str, -) -> Result, ControlError> { +) -> Result, ControlError> { if command == ADMIN_COMMAND { return run_admin(namespace).await.map(Some); } @@ -1184,7 +1215,7 @@ pub(crate) async fn run_control_action( .map(|()| None) } -/// Open and migrate the privileged store, reporting progress without contaminating JSON stdout. +/// Open and migrate the server's store, reporting progress on stderr. pub(crate) async fn open_control_store( namespace: &Namespace, server: Option<&ServerSection>, @@ -1193,14 +1224,17 @@ pub(crate) async fn open_control_store( namespace, &control_database_variable(namespace, server.unwrap_or(&ServerSection::default())), )?; + drop(write_output(&[(Stream::Stderr, OPENING_STORE)])); + let store = open_migrated_store(&url).await?; + drop(write_output(&[(Stream::Stderr, STORE_READY)])); + Ok(store) +} + +/// The store at `url`, created or migrated to this build's schema. +pub(crate) async fn open_migrated_store(url: &str) -> Result { set_release_version(env!("CARGO_PKG_VERSION")); - drop(write_output(&[( - Stream::Stderr, - "Opening control store...\n", - )])); - let store = open_store(&url).await?; + let store = open_store(url).await?; migrate_store(&store).await?; - drop(write_output(&[(Stream::Stderr, "Control store ready\n")])); Ok(store) } @@ -1547,11 +1581,18 @@ pub(crate) async fn next_turn( } /// `sqb dev`'s control lines from stdin; outside `sqb dev`, a fixed connected state. `sqb dev` holds stdin open while it lives, so its end, even after `sqb dev` was killed, stops the location as SIGTERM does. -pub(crate) fn dev_controls(options: &LocationServe) -> watch::Receiver { +pub(crate) fn dev_controls( + options: &LocationServe, +) -> ( + watch::Sender, + watch::Receiver, +) { let (sender, receiver) = watch::channel(DevControlState { warehouse: (!options.dev_events).then_some(true), recompiles: 0, + rediscovers: 0, }); + let republisher: watch::Sender = sender.clone(); if options.dev_events { tokio::task::spawn_blocking(move || { for line in std::io::stdin().lines().map_while(Result::ok) { @@ -1559,9 +1600,7 @@ pub(crate) fn dev_controls(options: &LocationServe) -> watch::Receiver { sender.send_modify(|state| state.warehouse = Some(connected)); } - Some(DevControl::Recompile) => { - sender.send_modify(|state| state.recompiles += 1); - } + Some(DevControl::Recompile) => request_republish(&sender, true), None => {} } } @@ -1572,7 +1611,15 @@ pub(crate) fn dev_controls(options: &LocationServe) -> watch::Receiver, rediscover: bool) { + controls.send_modify(|state| { + state.recompiles += 1; + state.rediscovers += u64::from(rediscover); + }); } /// Tell `sqb dev` which inputs changed since the last compile: the first few paths and how many more. @@ -1703,18 +1750,6 @@ pub(crate) async fn apply_dev_controls( Ok(settled.map(|settled| (control.recompiles, settled))) } -/// The loopback address `sqb dev` listens on. -pub(crate) fn loopback_address(namespace: &Namespace) -> Result { - let address = control_address(namespace, false, &ServerSection::default())? - .ok_or_else(|| ControlError::Invalid("development address is required".into()))?; - if !address.ip().is_loopback() { - return Err(ControlError::Invalid( - "sqb dev only listens on loopback".into(), - )); - } - Ok(address) -} - /// Open the development store, with its checklist row and the location it names on the screen. pub(crate) async fn announced_store( namespace: &Namespace, @@ -1802,6 +1837,8 @@ pub(crate) async fn development_store( target: target.into(), triggers: flag(namespace, "development_triggers"), principal_id: development_person(&store, &context).await?, + allowed_hosts: allowed_hosts(namespace)?, + listens_beyond_loopback: listens_beyond_loopback(namespace), }; if !scope.triggers { pause_development_triggers(&store, (location_id, target)).await?; @@ -1811,7 +1848,11 @@ pub(crate) async fn development_store( /// After a compile: a publication waits for the `sqb dev` warehouse verdict and settles; a failure keeps the last good snapshot. pub(crate) async fn finish_compile( - (options, script, session): (&LocationServe, &Path, (&str, Uuid)), + (options, script, (session, client)): ( + &LocationServe, + &Path, + ((&str, Uuid), &LocationWorkClient), + ), (load, generation): (LoadOutcome, i64), (mut watch, metadata, deferred): Settled, (controls, stopped): ( @@ -1820,9 +1861,22 @@ pub(crate) async fn finish_compile( ), ) -> Result, ControlError> { tokio::pin!(stopped); - let (refresh_at, locations, missing_secrets) = match load { + let owed: Option = watch.republish.take(); + let compiled = (&load, generation); + if let Some(result) = + settle_republish((client, session.1), owed, compiled, stopped.as_mut()).await + { + result?; + return Ok(None); + } + let LoadedGeneration { + refresh_at, + state_locations: locations, + secrets: missing_secrets, + .. + } = match load { Ok(published) => published, - Err(rules) => { + Err((rules, _)) => { watch.retry_at = Some(Instant::now() + Duration::from_secs(30)); tokio::select! { result = &mut stopped => { result?; return Ok(None); }, @@ -1898,25 +1952,6 @@ pub(crate) async fn compile_next_generation( Ok(load.map(|load| (Some((load, generation)), metadata, compiled_inputs))) } -/// Ask the runtime interpreter for one plan preview; its reply is one JSON line. -pub(crate) async fn exchange_location_plan( - compiler: &mut LocationCompiler, - request: &serde_json::Value, -) -> Result { - let mut line: Vec = serde_json::to_vec(request).map_err(std::io::Error::other)?; - line.push(b'\n'); - compiler.stdin.write_all(&line).await?; - compiler.stdin.flush().await?; - let mut reply = String::new(); - if compiler.stdout.read_line(&mut reply).await? == 0 { - return Err(ControlError::Invalid( - "location interpreter exited before replying".into(), - )); - } - serde_json::from_str(&reply) - .map_err(|_| ControlError::Invalid("location interpreter returned an invalid plan".into())) -} - /// The safety sync interval from the flag, then the environment, then the project; `None` when unset. pub(crate) fn safety_sync_setting( flag: Option<&str>, diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs index 0751361819..490625aafd 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs @@ -1,7 +1,12 @@ +pub(crate) mod api_start; pub(crate) mod changed_build; +pub(crate) mod compiler_discovery; +pub(crate) mod compiler_restart; pub(crate) mod dev_cancel; +pub(crate) mod dev_exposure; pub(crate) mod dev_start; pub(crate) mod dev_supervision; +pub(crate) mod discovery_state; pub(crate) mod dynamic_resume; pub(crate) mod env_reload; pub(crate) mod execution; @@ -10,6 +15,9 @@ pub(crate) mod plan_document; pub(crate) mod plan_request; pub(crate) mod plan_reuse; pub(crate) mod provider_secrets; +pub(crate) mod republish; +pub(crate) mod republish_caller; +pub(crate) mod republish_command; pub(crate) mod sensor_function; pub(crate) mod shutdown; pub(crate) mod sync_outcomes; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/provider_secrets.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/provider_secrets.rs index 14d00b0f29..b18761ae76 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/provider_secrets.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/provider_secrets.rs @@ -1,5 +1,9 @@ //! Reporting the providers a publication shows missing secrets. +use std::collections::BTreeMap; + +use sqlbuild_core::process_environment::main::env_file_shown::env_file_shown; +use sqlbuild_core::process_environment::main::location_secret_fix::location_secret_fix; use sqlbuild_orchestration::dev_events::main::emit_dev_event::emit_dev_event; use sqlbuild_orchestration::dev_events::models::{DevEvent, UnsetProviderSecrets}; use sqlbuild_orchestration::platform::main::health::unallowed_secret_count::unallowed_secret_count; @@ -10,20 +14,23 @@ use crate::argv::models::Stream; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::execution::report_location_health; use crate::native_commands::models::LocationServe; +use crate::native_commands::types::GenerationSecrets; -/// The providers whose missing secrets stop runs, by the variables they read: a provider the target allows to miss secrets is left out. +/// The providers whose missing secrets stop runs, with what needs each: a provider the target allows to miss secrets is left out. pub(crate) fn unset_provider_secrets( providers: &[MissingProviderSecrets], + needed_by: &BTreeMap>, ) -> Vec { let mut unset: Vec = Vec::new(); for provider in providers.iter().filter(|provider| !provider.allowed) { - let mut variables: Vec = Vec::new(); - for setting in &provider.settings { - variables.push(setting.variable.clone()); - } unset.push(UnsetProviderSecrets { provider: provider.provider.clone(), - variables, + path: provider.path.clone(), + settings: provider.settings.clone(), + needed_by: needed_by + .get(&provider.provider) + .cloned() + .unwrap_or_default(), }); } unset @@ -33,8 +40,9 @@ pub(crate) fn unset_provider_secrets( pub(crate) async fn report_provider_secrets( options: &LocationServe, (bearer, session_id): (&str, Uuid), - (generation, providers): (i64, Vec), + (generation, (providers, needed_by)): (i64, GenerationSecrets), ) { + let env_file: Option = env_file_shown(); let missing: u64 = unallowed_secret_count(&providers); if missing > 0 { let mut variables: Vec = Vec::new(); @@ -46,13 +54,15 @@ pub(crate) async fn report_provider_secrets( drop(write_output(&[( Stream::Stderr, &format!( - "Providers are missing secrets in this location's environment; runs that use them stop before the warehouse: {}\n", - variables.join(", ") + "Providers are missing secrets in this location's environment; runs that use them stop before the warehouse: {}\nTo fix, {}.\n", + variables.join(", "), + location_secret_fix("each variable", env_file.as_deref()) ), )])); } drop(emit_dev_event(&DevEvent::MissingSecrets { - providers: unset_provider_secrets(&providers), + providers: unset_provider_secrets(&providers, &needed_by), + env_file, })); report_location_health( options, diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish.rs new file mode 100644 index 0000000000..d9a19ab55b --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish.rs @@ -0,0 +1,140 @@ +//! What a republish published, reported back to the server before its claim ends. + +use std::future::Future; +use std::time::Duration; + +use sqlbuild_orchestration::api::errors::ClientError; +use sqlbuild_orchestration::platform::models::{ + LocationWork, LocationWorkClaim, LocationWorkClient, LocationWorkOutcome, LocationWorkResult, +}; +use sqlbuild_orchestration::store::errors::ControlError; +use tokio::sync::watch; +use tokio::time::Instant; +use uuid::Uuid; + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::execution::request_republish; +use crate::native_commands::models::{ + DevControlState, LocationWatch, LocationWorkTurn, PendingRepublish, +}; +use crate::native_commands::types::LoadOutcome; + +/// How long one result is retried while the watcher waits. +const REPORT_RETRY_WINDOW: Duration = Duration::from_secs(30); + +/// The outcome a compile gives the republish that asked for it. +fn republish_outcome(load: &LoadOutcome, generation: i64) -> LocationWorkOutcome { + match load { + Ok(published) => LocationWorkOutcome::Published { + snapshot_id: published.snapshot_id, + generation, + }, + Err((_, error)) => LocationWorkOutcome::PublishFailed { + generation, + error: error.clone(), + }, + } +} + +/// The turn that hands a claimed republish to the watch loop, which publishes it; `None` for other work. +pub(crate) fn republish_turn( + claim: &LocationWorkClaim, + deadline: Instant, +) -> Option { + let LocationWork::Republish { requested_by } = &claim.request.work else { + return None; + }; + drop(write_output(&[( + Stream::Stderr, + &format!( + "Republishing at the request of {requested_by}: {}\n", + claim.request.reason + ), + )])); + Some(LocationWorkTurn { + files: Vec::new(), + sync: false, + claimed: true, + republish: Some(PendingRepublish { + request_id: claim.request.request_id, + claim_id: claim.claim_id, + deadline, + }), + }) +} + +/// `location` owing `claimed` a result, with the compile it waits for started; unchanged without one. +pub(crate) fn start_republish( + republisher: &watch::Sender, + claimed: Option, + location: LocationWatch, +) -> LocationWatch { + let Some(claimed) = claimed else { + return location; + }; + request_republish(republisher, true); + LocationWatch { + retry_at: Some(Instant::now()), + republish: Some(claimed), + ..location + } +} + +/// Report what a compile published to the republish that waits for it; `Some` when shutdown came first. +pub(crate) async fn settle_republish( + session: (&LocationWorkClient, Uuid), + owed: Option, + (load, generation): (&LoadOutcome, i64), + stopped: impl Future>, +) -> Option> { + let pending: PendingRepublish = owed?; + tokio::select! { + result = stopped => Some(result), + () = report_republish(session, pending, republish_outcome(load, generation)) => None, + } +} + +/// Send the result, retrying a lost send briefly so an unreachable server cannot stall the watcher. +async fn report_republish( + (client, session_id): (&LocationWorkClient, Uuid), + pending: PendingRepublish, + outcome: LocationWorkOutcome, +) { + let result = LocationWorkResult { + claim_id: pending.claim_id, + session_id, + outcome, + }; + let retry_until: Instant = pending.deadline.min(Instant::now() + REPORT_RETRY_WINDOW); + while Instant::now() < retry_until { + let sent = + tokio::time::timeout_at(retry_until, client.complete(pending.request_id, &result)); + let Ok(sent) = sent.await else { + break; + }; + match sent { + Ok(_) => { + drop(write_output(&[( + Stream::Stderr, + "Republish result reported.\n", + )])); + return; + } + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!("Reporting the republish result failed: {error}\n"), + )])); + if matches!(error, ClientError::Rejected(status) if status.is_client_error()) { + return; + } + } + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + drop(write_output(&[( + Stream::Stderr, + "The republish's result could not be reported to the server.\n", + )])); +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish_caller.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish_caller.rs new file mode 100644 index 0000000000..35467e6889 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish_caller.rs @@ -0,0 +1,54 @@ +//! Who `sqb location republish` calls as: an API key over any transport, or a saved HTTPS session. + +use std::io::Error; + +use sqlbuild_orchestration::platform::main::work::call_remote_republish::call_remote_republish; +use sqlbuild_orchestration::platform::models::{RepublishCall, RepublishStatus}; +use uuid::Uuid; + +use crate::native_commands::constants::API_KEY_VARIABLE; +use crate::native_commands::models::RepublishCaller; +use crate::person_login::main::call_republish::call_republish; + +/// The environment's API key when there is one, otherwise the saved `sqb login` session. +pub(crate) fn republish_caller( + server: String, + ca: Option, +) -> Result { + let Some(key) = std::env::var_os(API_KEY_VARIABLE) else { + return Ok(RepublishCaller::Session { server, ca }); + }; + let key: String = key + .into_string() + .map_err(|_| Error::other(format!("{API_KEY_VARIABLE} must be UTF-8")))?; + if key.trim().is_empty() { + return Err(Error::other(format!( + "{API_KEY_VARIABLE} must not be blank" + ))); + } + if ca.is_some() { + return Err(Error::other(format!( + "--ca-cert applies only to a sqb login session, and {API_KEY_VARIABLE} is set" + ))); + } + Ok(RepublishCaller::Key { server, key }) +} + +/// The republish after `call`, made as `caller`. +pub(crate) fn call_as( + caller: &RepublishCaller, + scope: (Uuid, &str), + call: RepublishCall<'_>, +) -> Result { + let status: Option = match caller { + RepublishCaller::Key { server, key } => tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()? + .block_on(call_remote_republish((server, key), scope, call)) + .map_err(Error::other)?, + RepublishCaller::Session { server, ca } => { + call_republish((server, ca.as_deref()), scope, call)? + } + }; + status.ok_or_else(|| Error::other("the server has no such republish request")) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish_command.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish_command.rs new file mode 100644 index 0000000000..961c29fb76 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/republish_command.rs @@ -0,0 +1,98 @@ +//! `sqb location republish`: 0 accepted or published, 1 failed or expired, 2 unanswered or still pending. + +use std::io::Error; +use std::time::{Duration, Instant}; + +use sqlbuild_orchestration::platform::models::{ + PersonWorkRequest, RepublishCall, RepublishState, RepublishStatus, +}; +use uuid::Uuid; + +use crate::argv::models::{Namespace, Stream, Value}; +use crate::native_commands::_helpers::command::decision::{flag, text}; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::republish_caller::{call_as, republish_caller}; +use crate::native_commands::constants::{REPUBLISH_POLL_SECONDS, REPUBLISH_TIMEOUT_SECONDS}; + +pub(crate) fn run_republish(namespace: &Namespace) -> i32 { + drop(write_output(&[( + Stream::Stderr, + "Requesting a republish…\n", + )])); + let waits: bool = flag(namespace, "location_wait"); + let result: Result<(RepublishStatus, String), Error> = + republished(namespace, waits).and_then(|status| { + let document: String = serde_json::to_string(&status).map_err(Error::other)?; + Ok((status, document)) + }); + match result { + Ok((status, document)) => { + let (summary, code): (&str, i32) = match (status.state, waits) { + (RepublishState::Published, _) => ("Republish published a snapshot", 0), + (RepublishState::Failed, _) => ("Republish failed", 1), + (RepublishState::Expired, _) => ("Republish expired before a location took it", 1), + (RepublishState::Pending, false) => ("Republish accepted", 0), + (RepublishState::Pending, true) => ("Republish is still pending", 2), + }; + let detail: String = status + .error + .map(|error| format!(": {error}")) + .unwrap_or_default(); + drop(write_output(&[ + (Stream::Stdout, &format!("{document}\n")), + (Stream::Stderr, &format!("{summary}{detail}\n")), + ])); + code + } + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!("Republish request failed: {error}\n"), + )])); + 2 + } + } +} + +fn republished(namespace: &Namespace, waits: bool) -> Result { + let location: Uuid = text(namespace, "location_id") + .unwrap_or_default() + .parse() + .map_err(|_| Error::other("--location-id must be a UUID"))?; + let target: String = text(namespace, "target").unwrap_or_default(); + let timeout: u64 = match namespace.get("location_timeout") { + Some(Value::Int(seconds)) => seconds + .parse() + .map_err(|_| Error::other("--timeout must be a number of seconds, zero or more"))?, + _ => REPUBLISH_TIMEOUT_SECONDS, + }; + let deadline: Instant = Instant::now() + .checked_add(Duration::from_secs(timeout)) + .ok_or_else(|| Error::other("--timeout is too large"))?; + let caller = republish_caller( + text(namespace, "location_server_url").unwrap_or_default(), + text(namespace, "login_ca").map(std::path::PathBuf::from), + )?; + let request = PersonWorkRequest { + request_id: Uuid::now_v7(), + reason: text(namespace, "location_reason") + .unwrap_or_else(|| "Requested from the CLI".to_owned()), + }; + let mut status: RepublishStatus = call_as( + &caller, + (location, &target), + RepublishCall::Request(&request), + )?; + while waits && status.state == RepublishState::Pending { + let left: u64 = deadline.saturating_duration_since(Instant::now()).as_secs(); + if left == 0 { + break; + } + let read = RepublishCall::Read { + request_id: request.request_id, + wait: left.min(REPUBLISH_POLL_SECONDS), + }; + status = call_as(&caller, (location, &target), read)?; + } + Ok(status) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs index a4bc0c525f..bbfa7678cf 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod admin; pub(crate) mod command; pub(crate) mod location; pub(crate) mod sensor_trial; diff --git a/crates/sqlbuild-cli/src/native_commands/constants.rs b/crates/sqlbuild-cli/src/native_commands/constants.rs index 4e20c2f681..da3c86e875 100644 --- a/crates/sqlbuild-cli/src/native_commands/constants.rs +++ b/crates/sqlbuild-cli/src/native_commands/constants.rs @@ -87,6 +87,18 @@ pub(crate) const SCHEDULER_COMMAND: &str = "scheduler"; pub(crate) const ADMIN_COMMAND: &str = "admin"; +/// How long `sqb admin` opens its store in silence; a migration or a busy store takes longer. +pub(crate) const ADMIN_OPEN_NOTICE: std::time::Duration = std::time::Duration::from_secs(1); +/// Printed when opening the control store starts. +pub(crate) const OPENING_STORE: &str = "Opening control store...\n"; +/// Printed when the control store is open. +pub(crate) const STORE_READY: &str = "Control store ready\n"; +/// An admin command committed, and its result didn't reach stdout. +pub(crate) const ADMIN_DELIVERY_FAILED: &str = + "Control administration result delivery failed; changes may already be committed\n"; +/// How a table shows a value that is absent. +pub(crate) const NO_VALUE: &str = "-"; + pub(crate) const RULES_COMMAND: &str = "rules"; pub(crate) const RULES_LIST_ACTION: &str = "list"; @@ -250,3 +262,13 @@ pub(crate) const SENSOR_COMMAND: &str = "sensor"; pub(crate) const SENSOR_USAGE_EXIT: i32 = 2; /// Exit status when the function failed, timed out, or there was nothing to call it with. pub(crate) const SENSOR_FAILED_EXIT: i32 = 1; + +/// The environment variable `sqb location republish` reads an API key from; never an argument. +pub(crate) const API_KEY_VARIABLE: &str = "SQLBUILD_API_KEY"; +/// How long one `--wait` poll holds its response open, inside both clients' request timeouts. +pub(crate) const REPUBLISH_POLL_SECONDS: u64 = 10; +/// How long `sqb location republish --wait` waits unless told otherwise. +pub(crate) const REPUBLISH_TIMEOUT_SECONDS: u64 = 600; + +/// How `sqb dev` hands its location the resolved folder of run output, which the watch leaves out. +pub(crate) const DEVELOPMENT_OUTPUT_FOLDER: &str = "SQLBUILD_DEVELOPMENT_OUTPUT_FOLDER"; diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs index 79078ecdf6..15febaebbb 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs @@ -31,7 +31,11 @@ pub(super) async fn report_changed_build( stopped: impl Future>, ) -> Result, ControlError> { let published = || { - location_files(&options.project_dir, &watch.rules, &watch.local_files) == watch.observed.0 + location_files( + &options.project_dir, + &watch.rules, + (&watch.local_files, &watch.output_folders), + ) == watch.observed.0 }; let report = |message: &str| drop(write_output(&[(Stream::Stderr, message)])); if !published() { diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs index 2bc283d094..4a00e7f3c8 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs @@ -3,39 +3,64 @@ use std::path::Path; use sqlbuild_cache::project_snapshot::models::PathStamp; -use sqlbuild_orchestration::dev_events::main::dev_event_line::dev_event_line; -use sqlbuild_orchestration::dev_events::models::DevEvent; use sqlbuild_orchestration::store::errors::ControlError; use tokio::sync::mpsc; +use tokio::time::Instant; -use crate::argv::models::Stream; -use crate::native_commands::_helpers::command::terminal::write_output; -use crate::native_commands::_helpers::location::env_reload::reload_env_file; -use crate::native_commands::_helpers::location::execution::{ - exchange_location_generation, exchange_location_plan, +use crate::native_commands::_helpers::location::compiler_discovery::{ + check_discovered, discovered, sleep_until, }; +use crate::native_commands::_helpers::location::compiler_restart::restarted_for_changes; +use crate::native_commands::_helpers::location::discovery_state::LocationDiscovery; +use crate::native_commands::_helpers::location::execution::exchange_reply; use crate::native_commands::_helpers::location::execution::{ open_location_runtime, stop_location_runtime, }; use crate::native_commands::models::{ - LocationCompileRequest, LocationCompiler, LocationPlanRequest, LocationRuntimeRequest, - LocationServe, + LocationCompileRequest, LocationCompiler, LocationLoad, LocationPlanRequest, + LocationRuntimeRequest, LocationServe, }; +use crate::native_commands::types::DiscoveryControls; pub(crate) async fn run_location_compiler( options: &LocationServe, script: &Path, mut requests: mpsc::Receiver, + controls: DiscoveryControls<'_>, ) -> Result<(), ControlError> { let mut compiler: Option = None; let mut sources: Vec = Vec::new(); + let mut discovery: LocationDiscovery = LocationDiscovery::default(); let result = async { - while let Some(request) = requests.recv().await { + loop { + let due: Option = discovery.next_due().filter(|_| compiler.is_some()); + let request: Option = tokio::select! { + request = requests.recv() => match request { + Some(request) => Some(request), + None => break, + }, + () = sleep_until(due) => None, + }; + let Some(request) = request else { + compiler = check_discovered(compiler.take(), &mut discovery, (controls, &requests)) + .await?; + if requests.is_closed() { + break; + } + continue; + }; let carried_on; (compiler, carried_on) = match request { LocationRuntimeRequest::Publish(request) => { - sources.clone_from(&request.python_sources); - publish((options, script), compiler.take(), request).await? + let before: Vec = + std::mem::replace(&mut sources, request.python_sources.clone()); + publish( + (options, script), + compiler.take(), + (request, &before), + (&mut discovery, controls), + ) + .await? } LocationRuntimeRequest::Plan(request) => { plan( @@ -60,37 +85,30 @@ pub(crate) async fn run_location_compiler( /// Publish one generation; false when its requester stopped waiting, which only shutdown does. async fn publish( (options, script): (&LocationServe, &Path), - mut compiler: Option, - mut request: LocationCompileRequest, + compiler: Option, + (mut request, before): (LocationCompileRequest, &[PathStamp]), + (discovery, (republish, (bearer, session_id))): (&mut LocationDiscovery, DiscoveryControls<'_>), ) -> Result<(Option, bool), ControlError> { - let env_changed: bool = reload_env_file(options); - let python_changed: bool = compiler - .as_ref() - .is_some_and(|compiler| compiler.python_sources != request.python_sources); - if compiler.is_some() && (python_changed || env_changed) { - stop_location_runtime(compiler.take()).await?; - if options.dev_events { - let reason: &str = if python_changed { - "Python changed" - } else { - "env file changed" - }; - drop(write_output(&[( - Stream::Stdout, - &dev_event_line(&DevEvent::Restarted { - reason: reason.into(), - }), - )])); - } - } + let compiler: Option = + restarted_for_changes(options, compiler, &request.python_sources).await?; + let publication = discovery.publish_request( + request.generation, + (before, &request.python_sources), + republish.borrow().rediscovers, + ); let mut active = match compiler { Some(active) => active, - None => open_location_runtime(options, script, request.python_sources)?, + None => open_location_runtime(options, script, request.python_sources.clone())?, }; let result = tokio::select! { _ = request.reply.closed() => return Ok((Some(active), false)), - result = exchange_location_generation(&mut active, request.generation) => result, + result = exchange_reply::(&mut active, &publication, "publication record") => result, }; + if let Ok(load) = &result { + let session = (bearer, session_id); + discovered(options, session, (request.generation, load, &*discovery)).await; + discovery.published(load, Instant::now()); + } let failed = result.is_err(); let _ = request .reply @@ -113,7 +131,7 @@ async fn plan( None => open_location_runtime(options, script, sources.to_vec())?, }; let result = { - let exchange = exchange_location_plan(&mut active, &request.request); + let exchange = exchange_reply::(&mut active, &request.request, "plan"); tokio::pin!(exchange); tokio::select! { () = request.reply.closed() => { diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs index eaab7273b5..4075792e6b 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs @@ -29,8 +29,11 @@ pub(crate) async fn sync_location_metadata( ) -> Result, ControlError> { if Instant::now() < state.next_at || state.locations.is_empty() - || location_files(&options.project_dir, &watch.rules, &watch.local_files) - != watch.observed.0 + || location_files( + &options.project_dir, + &watch.rules, + (&watch.local_files, &watch.output_folders), + ) != watch.observed.0 { return Ok(Some(state)); } @@ -88,8 +91,11 @@ pub(crate) async fn sync_location_metadata( .await; } }; - if location_files(&options.project_dir, &watch.rules, &watch.local_files) - != watch.observed.0 + if location_files( + &options.project_dir, + &watch.rules, + (&watch.local_files, &watch.output_folders), + ) != watch.observed.0 { return Ok(Some(state)); } diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs index bec64273ca..1226c53182 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs @@ -19,6 +19,7 @@ use crate::native_commands::_helpers::command::paths::location_files; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::execution::check_location_connection; use crate::native_commands::_helpers::location::plan_reuse::keep_plan; +use crate::native_commands::_helpers::location::republish::republish_turn; use crate::native_commands::_helpers::location::sensor_function::run_sensor_function; use crate::native_commands::_helpers::location::work::work_error; use crate::native_commands::main::_location_plan::plan_location; @@ -41,24 +42,28 @@ pub(super) async fn run_location_work( let claim = tokio::select! { result = &mut stopped => { result?; return Ok(None); }, result = client.poll(poll) => match result { - Ok(claim) => claim, + Ok(Some(claim)) => claim, + Ok(None) => return Ok(Some(LocationWorkTurn::default())), Err(error) => { work_error(&error)?; return Ok(Some(LocationWorkTurn::default())); }, }, }; - let Some(claim) = claim else { - return Ok(Some(LocationWorkTurn::default())); - }; let deadline = Instant::now() + (claim.lease_expires_at - Utc::now()) .to_std() .unwrap_or_default(); + if let Some(turn) = republish_turn(&claim, deadline) { + return Ok(Some(turn)); + } let mut files: Vec = Vec::new(); let outcome = if generation == Some(claim.generation) - && location_files(&options.project_dir, &watch.rules, &watch.local_files) - == watch.observed.0 + && location_files( + &options.project_dir, + &watch.rules, + (&watch.local_files, &watch.output_folders), + ) == watch.observed.0 { let mut shutting_down = false; let expires = async { @@ -84,6 +89,7 @@ pub(super) async fn run_location_work( files, sync: false, claimed: true, + republish: None, })); }; files = local_files; @@ -93,7 +99,12 @@ pub(super) async fn run_location_work( .retain(|stamp| !files.contains(&options.project_dir.join(&stamp.relative_path))); let mut excluded = watch.local_files.clone(); excluded.extend(files.clone()); - if location_files(&options.project_dir, &watch.rules, &excluded) == expected.0 { + if location_files( + &options.project_dir, + &watch.rules, + (&excluded, &watch.output_folders), + ) == expected.0 + { if let LocationWorkOutcome::Plan { document, diffs } = &outcome { keep_plan(keep, (document, diffs)); } @@ -126,6 +137,7 @@ pub(super) async fn run_location_work( files, sync, claimed: true, + republish: None, })); } Err(error) => { @@ -148,6 +160,7 @@ pub(super) async fn run_location_work( files, sync, claimed: true, + republish: None, })) } @@ -167,9 +180,11 @@ async fn perform_work( LocationWork::SyncWarehouse {} => "Synchronizing warehouse history on request...\n", LocationWork::EvaluateSensor { .. } => "Running a sensor's function...\n", LocationWork::Plan { .. } => "Planning requested command...\n", + LocationWork::Republish { .. } => "Republishing on request...\n", }; drop(write_output(&[(Stream::Stderr, message)])); Ok(match work { + LocationWork::Republish { .. } => None, LocationWork::SyncWarehouse {} => { Some((LocationWorkOutcome::SyncStarted {}, Vec::new(), None)) } diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs index 3adc7665aa..e3eaa34e6a 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_admin.rs @@ -1,144 +1,87 @@ //! Direct database ownership authorizes bootstrap, not an untrusted HTTP request or supplied role. -use crate::adhoc::main::adhoc_planner::adhoc_planner; -use serde_json::{Value, json}; use sqlbuild_orchestration::authorization::main::people::bootstrap_user::bootstrap_user; -use sqlbuild_orchestration::authorization::main::roles::grant_admin::grant_admin; use sqlbuild_orchestration::credentials::main::identities::create_principal::create_principal; use sqlbuild_orchestration::credentials::main::locations::create_location::create_location; -use sqlbuild_orchestration::credentials::main::sessions::set_password::set_password; -use sqlbuild_orchestration::credentials::main::tokens::issue_token::issue_token; -use sqlbuild_orchestration::credentials::main::tokens::revoke_token::revoke_token; -use sqlbuild_orchestration::credentials::main::tokens::rotate_token::rotate_token; -use sqlbuild_orchestration::credentials::models::{AuditContext, PasswordAuthority}; -use sqlbuild_orchestration::declarations::main::change_trigger::change_trigger; +use sqlbuild_orchestration::credentials::models::AuditContext; use sqlbuild_orchestration::declarations::models::TriggerChangeRequest; -use sqlbuild_orchestration::platform::main::work::location_work::location_work; -use sqlbuild_orchestration::platform::main::work::request_location_work::request_location_work; -use sqlbuild_orchestration::runs::main::execution::change_run::change_run; -use sqlbuild_orchestration::runs::main::requests::request_job_run::request_job_run; -use sqlbuild_orchestration::runs::main::requests::request_rerun::request_rerun; -use sqlbuild_orchestration::runs::models::JobRunRequest; -use sqlbuild_orchestration::runs::models::{RunAuthority, RunChange, RunChangeRequest}; use sqlbuild_orchestration::store::errors::ControlError; use sqlbuild_orchestration::store::models::ControlStore; use uuid::Uuid; use crate::argv::models::Namespace; +use crate::native_commands::_helpers::admin::people::{provide_password, restore_admin}; +use crate::native_commands::_helpers::admin::requests::{ + override_trigger, queue_job_run, queue_rerun, read_request, request_cancellation, request_check, +}; +use crate::native_commands::_helpers::admin::store::open_admin_store; +use crate::native_commands::_helpers::command::admin_actions::{ + run_service_account_admin, run_token_admin, +}; use crate::native_commands::_helpers::command::decision::control_admin; -use crate::native_commands::_helpers::location::execution::open_control_store; -use crate::native_commands::models::ControlAdmin; +use crate::native_commands::models::{AdminDone, ControlAdmin}; -pub(crate) async fn run_admin(namespace: &Namespace) -> Result { - let action = control_admin(namespace)?; - let store = open_control_store(namespace, None).await?; +pub(crate) async fn run_admin(namespace: &Namespace) -> Result { + let action: ControlAdmin = control_admin(namespace)?; + let store: ControlStore = open_admin_store(namespace).await?; let context = AuditContext { actor: "local-control-store-owner".into(), granting_role: "control-store-owner".into(), request_id: Uuid::now_v7(), ip_address: None, }; + perform(&store, &context, action).await +} + +async fn perform( + store: &ControlStore, + context: &AuditContext, + action: ControlAdmin, +) -> Result { match action { - ControlAdmin::BootstrapUser(name) => { - let id = bootstrap_user(&store, &context, &name).await?; - Ok(json!({"principal_id":id,"name":name,"kind":"person","role":"admin"})) - } - ControlAdmin::CreateLocation(name) => { - let id = create_location(&store, &name, &context).await?; - Ok(json!({"location_id": id, "name": name})) - } - ControlAdmin::CreatePrincipal(name) => { - let id = create_principal(&store, &context, &name).await?; - Ok(json!({"principal_id": id, "name": name})) - } - ControlAdmin::IssueToken(scope, expires_at) => { - let token = issue_token(&store, &context, scope, expires_at).await?; - Ok(json!(token)) - } - ControlAdmin::RevokeToken(token_id) => { - let revoked = revoke_token(&store, &context, token_id).await?; - Ok(json!({"token_id": token_id, "revoked": revoked})) - } - ControlAdmin::RotateToken(token_id) => { - Ok(json!(rotate_token(&store, &context, token_id).await?)) - } - ControlAdmin::SetPassword(principal_id, password) => { - set_password( - &store, - &context, - PasswordAuthority::Operator(principal_id), - &password, - ) - .await?; - Ok(json!({"principal_id": principal_id, "password_set": true})) - } - ControlAdmin::GrantAdmin(principal_id) => { - grant_admin(&store, &context, principal_id).await?; - Ok(json!({"principal_id": principal_id, "role": "admin"})) - } - ControlAdmin::RequestJobRun(request) => queue_job_run(&store, &context, &request).await, - ControlAdmin::Rerun(request) => { - let applied = request_rerun(&store, (&context, None), &request).await?; - Ok(json!({"run_id": request.run_id, "applied": applied})) - } - ControlAdmin::RequestLocationWork(request) => { - let applied = request_location_work(&store, (&context, None), &request).await?; - Ok(json!({"request_id": request.request_id, "applied": applied})) - } - ControlAdmin::LocationWork(request_id) => { - Ok(json!(location_work(&store, request_id).await?)) + ControlAdmin::BootstrapUser(name) => Ok(AdminDone::Bootstrapped { + id: bootstrap_user(store, context, &name).await?, + name, + }), + ControlAdmin::CreateLocation(name) => Ok(AdminDone::LocationCreated { + id: create_location(store, &name, context).await?, + name, + }), + ControlAdmin::CreatePrincipal(name) => Ok(AdminDone::PrincipalCreated { + id: create_principal(store, context, &name).await?, + name, + }), + ControlAdmin::Token(action) => run_token_admin(store, context, action).await, + ControlAdmin::SetPassword(id, password) => { + provide_password(store, context, (id, password)).await } + ControlAdmin::GrantAdmin(id) => restore_admin(store, context, id).await, + ControlAdmin::RequestJobRun(request) => queue_job_run(store, context, request).await, + ControlAdmin::Rerun(request) => queue_rerun(store, context, request).await, + ControlAdmin::RequestLocationWork(request) => request_check(store, context, request).await, + ControlAdmin::LocationWork(request_id) => read_request(store, request_id).await, ControlAdmin::CancelRun { event_id, run_id, reason, - } => { - let applied = change_run( - &store, - RunAuthority::Operator(&context), - &RunChangeRequest { - event_id, - run_id, - claim_id: None, - change: RunChange::CancelRequested { - actor: context.actor.clone(), - reason, - }, - }, - ) - .await?; - Ok(json!({"event_id": event_id, "run_id": run_id, "applied": applied})) - } + } => request_cancellation(store, context, (event_id, run_id, reason)).await, ControlAdmin::ChangeTrigger { event_id, trigger_id, change, reason, } => { - let applied = change_trigger( - &store, - &context, - &TriggerChangeRequest { - event_id, - trigger_id, - actor: context.actor.clone(), - reason, - change, - }, - ) - .await?; - Ok(json!({"event_id": event_id, "trigger_id": trigger_id, "applied": applied})) + let request = TriggerChangeRequest { + event_id, + trigger_id, + actor: context.actor.clone(), + reason, + change, + }; + override_trigger(store, context, request).await + } + ControlAdmin::ServiceAccount(action) => { + run_service_account_admin(store, context, action).await } } } - -/// A trusted job run, narrowed with the same planner the server resolves ad-hoc commands with. -async fn queue_job_run( - store: &ControlStore, - context: &AuditContext, - request: &JobRunRequest, -) -> Result { - let planner = adhoc_planner(); - let applied = request_job_run(store, (context, Some(planner.as_ref())), request).await?; - Ok(json!({"run_id": request.run_id, "applied": applied})) -} diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs index 0962a26722..666c7657e1 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs @@ -1,7 +1,5 @@ //! Supervise native API/scheduler roles together; a failed role stops its siblings. -use sqlbuild_orchestration::api::main::serve_api::serve_api; -use sqlbuild_orchestration::platform::models::RetentionPolicies; use sqlbuild_orchestration::scheduler::main::run_scheduler::run_scheduler; use sqlbuild_orchestration::scheduler::models::SchedulerState; use sqlbuild_orchestration::store::errors::ControlError; @@ -11,23 +9,18 @@ use tokio::task::JoinSet; use uuid::Uuid; use crate::argv::models::{Namespace, Stream}; -use crate::native_commands::_helpers::command::decision::{control_address, control_api_settings}; +use crate::native_commands::_helpers::command::decision::{ + control_address, control_api_settings, control_output, +}; use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::api_start::start_api; use crate::native_commands::_helpers::location::execution::{ - open_control_store, open_control_workers, start_platform_roles, + open_control_store, open_control_workers, }; use crate::native_commands::_helpers::location::shutdown::supervise_control_roles; use crate::server_config::main::read_server_config::read_server_config; use crate::workers::models::Workers; -async fn stopped(mut shutdown: watch::Receiver) { - while !*shutdown.borrow_and_update() { - if shutdown.changed().await.is_err() { - break; - } - } -} - pub(crate) async fn run_control( namespace: &Namespace, standalone: bool, @@ -36,6 +29,7 @@ pub(crate) async fn run_control( let address = control_address(namespace, standalone, &config.server)?; let (authentication, mut facts) = control_api_settings(namespace, standalone, &config)?; let store = open_control_store(namespace, Some(&config.server)).await?; + let run_output = control_output(namespace, &config, (&store, &mut facts))?; let (workers, handoff) = open_control_workers( (&store, namespace), (&config.server, config.launchers), @@ -46,37 +40,13 @@ pub(crate) async fn run_control( let (stop, shutdown) = watch::channel(false); let mut tasks = JoinSet::new(); if let Some(address) = address { - drop(write_output(&[( - Stream::Stderr, - "Starting control API...\n", - )])); - let listener = tokio::net::TcpListener::bind(address).await?; - let address = listener.local_addr()?; - tasks.spawn(serve_api( - store.clone(), - listener, - (authentication, handoff, facts.clone()), - ( - move || { - drop(write_output(&[( - Stream::Stderr, - &format!("Control API ready: {address}\n"), - )])); - }, - stopped(shutdown.clone()), - ), - )); - start_platform_roles( - &mut tasks, - (&store, &shutdown), - RetentionPolicies { - audit: facts.audit, - statistics: facts.statistics, - snapshots: facts.snapshots, - run_logs: facts.run_logs, - state_history: facts.state_history, - }, - )?; + tasks = start_api( + tasks, + (address, &store, &shutdown), + (authentication, handoff, &facts), + run_output, + ) + .await?; } if facts.scheduler { start_scheduler(&mut tasks, (store, facts.origin.clone()), shutdown, workers); diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs index 11fbfc7af7..872d252703 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs @@ -1,5 +1,6 @@ //! Coalesce source edits and retain the last good publication across isolated compiler failures. +use sqlbuild_orchestration::platform::models::LocationWorkScope; use std::future::Future; use std::path::Path; use std::time::Duration; @@ -24,6 +25,7 @@ use crate::native_commands::_helpers::location::execution::{ use crate::native_commands::_helpers::location::execution::{ dev_controls, location_clock, location_heartbeats, next_turn, }; +use crate::native_commands::_helpers::location::republish::start_republish; use crate::native_commands::_helpers::location::shutdown::shutdown_signal; use crate::native_commands::_helpers::location::work::next_work_check; use crate::native_commands::constants::LOCATION_WORK_IDLE_POLL; @@ -47,17 +49,25 @@ pub(super) async fn run_location( let poll = LocationWorkPoll { session_id, target: options.target.clone(), + scope: LocationWorkScope::All, }; let (requests, receiver) = mpsc::channel(1); - let controls = dev_controls(&options); + let (republisher, controls) = dev_controls(&options); let serving = async { tokio::select! { - result = watch_location(&options, script, (bearer, &client, &poll), (requests, controls)) => result, + result = watch_location(&options, script, (bearer, &client, &poll), (requests, controls, &republisher)) => result, result = location_heartbeats(&options, bearer, session_id) => result, } }; - let (serving, compiler) = - tokio::join!(serving, run_location_compiler(&options, script, receiver)); + let (serving, compiler) = tokio::join!( + serving, + run_location_compiler( + &options, + script, + receiver, + (&republisher, (bearer, session_id)) + ) + ); serving.and(compiler) } @@ -65,9 +75,10 @@ async fn watch_location( options: &LocationServe, script: &Path, (bearer, client, poll): (&str, &LocationWorkClient, &LocationWorkPoll), - (requests, mut controls): ( + (requests, mut controls, republisher): ( mpsc::Sender, watch::Receiver, + &watch::Sender, ), ) -> Result<(), ControlError> { let mut watch = location_watch(&options.project_dir); @@ -111,7 +122,7 @@ async fn watch_location( let connected: bool = controls.borrow().warehouse == Some(true); let Some(idle) = poll_location( (options, script, (&requests, connected)), - (client, poll, published_generation), + (client, poll, (published_generation, republisher)), (watch, work_at, metadata), stopped.as_mut(), ) @@ -143,7 +154,7 @@ async fn watch_location( Err(_) => None, }; let Some(settled) = finish_compile( - (options, script, (bearer, poll.session_id)), + (options, script, ((bearer, poll.session_id), client)), (load, generation), (watch, metadata, deferred_sync), (&mut controls, stopped.as_mut()), @@ -163,16 +174,28 @@ async fn poll_location( &Path, (&mpsc::Sender, bool), ), - (client, poll, generation): (&LocationWorkClient, &LocationWorkPoll, Option), + (client, poll, (generation, republisher)): ( + &LocationWorkClient, + &LocationWorkPoll, + (Option, &watch::Sender), + ), (mut watch, mut work_at, mut metadata): (LocationWatch, Instant, Option), stopped: impl Future>, ) -> Result)>, ControlError> { tokio::pin!(stopped); - if generation.is_some() && watch.attempted.as_ref() == Some(&watch.observed) { + let current: bool = watch.attempted.as_ref() == Some(&watch.observed); + if current { if Instant::now() >= work_at { + let poll = LocationWorkPoll { + scope: match generation { + Some(_) => LocationWorkScope::All, + None => LocationWorkScope::RepublishOnly, + }, + ..poll.clone() + }; let Some(turn) = run_location_work( (options, script, (runtime, connected)), - (client, poll, &watch), + (client, &poll, &watch), generation, stopped.as_mut(), ) @@ -181,6 +204,7 @@ async fn poll_location( return Ok(None); }; work_at = next_work_check(&turn, Instant::now()); + watch = start_republish(republisher, turn.republish, watch); watch = exclude_location_databases(&options.project_dir, turn.files, watch); if turn.sync && let Some(state) = metadata.as_mut() @@ -188,7 +212,9 @@ async fn poll_location( state.request_sync(); } } - if let Some(state) = metadata.take() { + if generation.is_some() + && let Some(state) = metadata.take() + { let syncing = !state.idle; metadata = sync_location_metadata( state, diff --git a/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs b/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs index 6efc185ff7..854ce8c29c 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs @@ -36,7 +36,7 @@ pub(crate) fn parse_native_invocation(arguments: &[OsString]) -> Result Option { let role = if admin { "administration" } else { "service" }; let result = runtime.block_on(run_control_action(namespace, &command)); Some(match result { - Ok(output) => { - let lost = - output.and_then(|value| write_output(&[(Stream::Stdout, &format!("{value}\n"))])); - if admin && lost.is_some() { - drop(write_output(&[( - Stream::Stderr, - &format!( - "Control {role} JSON result delivery failed; changes may already be committed\n" - ), - )])); - return Some(1); - } - let exit_code = finish_lost_stdout(lost.as_ref(), 0); - if exit_code == 0 { - let message = if admin { - "Control administration completed successfully\n" - } else { - "Control service stopped successfully\n" - }; - drop(write_output(&[(Stream::Stderr, message)])); - } - exit_code + Ok(Some(done)) => deliver_admin_result(&done, flag(namespace, "json")), + Ok(None) => { + drop(write_output(&[( + Stream::Stderr, + "Control service stopped successfully\n", + )])); + 0 } Err(error) => { drop(write_output(&[( diff --git a/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs b/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs index ec18abe481..1d2fb6f694 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs @@ -12,6 +12,7 @@ use crate::argv::models::{Namespace, Stream}; use crate::native_commands::_helpers::command::decision::text; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::execution::location_options; +use crate::native_commands::_helpers::location::republish_command::run_republish; use crate::native_commands::main::_run_dev::run_development; use crate::native_commands::main::_run_location::run_location; @@ -25,6 +26,9 @@ pub(crate) fn run_location_invocation(namespace: &Namespace, script: Option<&Pat if !development && location_command.as_deref() == Some("health") { return Some(location_health(namespace)); } + if !development && location_command.as_deref() == Some("republish") { + return Some(run_republish(namespace)); + } if !development && location_command.as_deref() != Some("serve") { return None; } @@ -65,7 +69,7 @@ pub(crate) fn run_location_invocation(namespace: &Namespace, script: Option<&Pat }) } -/// `sqb location health`: 0 when healthy or degraded, 1 when down or falling back, 2 when unanswered. +/// `sqb location health`: 0 when healthy, degraded or failing discovery, 1 when down or falling back, 2 when unanswered. fn location_health(namespace: &Namespace) -> i32 { drop(write_output(&[( Stream::Stderr, diff --git a/crates/sqlbuild-cli/src/native_commands/models.rs b/crates/sqlbuild-cli/src/native_commands/models.rs index d65a409ae1..2a65c1f148 100644 --- a/crates/sqlbuild-cli/src/native_commands/models.rs +++ b/crates/sqlbuild-cli/src/native_commands/models.rs @@ -6,9 +6,13 @@ use std::path::PathBuf; use chrono::{DateTime, Utc}; use sqlbuild_cache::project_snapshot::models::{PathStamp, SnapshotRules}; -use sqlbuild_orchestration::credentials::models::CredentialScope; +use sqlbuild_orchestration::credentials::models::{ + CredentialScope, IssuedToken, NewServiceAccount, ServiceAccountSummary, +}; use sqlbuild_orchestration::declarations::models::TriggerChange; -use sqlbuild_orchestration::platform::models::{LocationWorkRequest, WarehouseReadFailure}; +use sqlbuild_orchestration::platform::models::{ + LocationWorkRecord, LocationWorkRequest, WarehouseReadFailure, +}; use sqlbuild_orchestration::runs::models::{JobRunRequest, RerunRequest}; use sqlbuild_orchestration::sensors::models::SensorEventChoice; use sqlbuild_orchestration::warehouse_metadata::constants::MAX_HISTORY_PAGE_RECORDS; @@ -26,9 +30,7 @@ pub(crate) enum ControlAdmin { CreateLocation(String), CreatePrincipal(String), BootstrapUser(String), - IssueToken(CredentialScope, DateTime), - RevokeToken(Uuid), - RotateToken(Uuid), + Token(TokenAdmin), SetPassword(Uuid, String), GrantAdmin(Uuid), RequestJobRun(JobRunRequest), @@ -46,6 +48,116 @@ pub(crate) enum ControlAdmin { change: TriggerChange, reason: String, }, + ServiceAccount(ServiceAccountAdmin), +} + +/// The location token commands. +#[derive(Debug)] +pub(crate) enum TokenAdmin { + Issue(CredentialScope, DateTime), + Revoke(Uuid), + Rotate(Uuid), +} + +/// The service account commands, which name accounts rather than numbering them. +pub(crate) enum ServiceAccountAdmin { + /// A new account, with the key read from `--key-from-env` when one is imported. + Create { + request: NewServiceAccount, + key: Option, + }, + Rotate { + name: String, + overlap_minutes: i64, + }, + SetDisabled { + name: String, + disabled: bool, + }, + List, +} + +/// What an admin command did or read; it may hold a secret, so it has no `Debug`. +pub(crate) enum AdminDone { + Bootstrapped { + id: Uuid, + name: String, + }, + LocationCreated { + id: Uuid, + name: String, + }, + PrincipalCreated { + id: Uuid, + name: String, + }, + PasswordSet { + id: Uuid, + name: String, + }, + AdminGranted { + id: Uuid, + name: String, + }, + TokenIssued { + token: IssuedToken, + location: String, + }, + TokenRotated { + replaced: Uuid, + token: IssuedToken, + }, + TokenRevoked { + id: Uuid, + revoked: bool, + }, + RunQueued { + run_id: Uuid, + job: String, + target: String, + applied: bool, + }, + RerunQueued { + run_id: Uuid, + source: Uuid, + applied: bool, + }, + CheckRequested { + request_id: Uuid, + location: String, + target: String, + applied: bool, + }, + WorkRead { + request_id: Uuid, + record: Option>, + now: DateTime, + }, + CancelRequested { + event_id: Uuid, + run_id: Uuid, + applied: bool, + }, + TriggerChanged { + event_id: Uuid, + trigger_id: Uuid, + change: TriggerChange, + applied: bool, + }, + /// `key` is absent when the operator imported their own. + AccountCreated { + account: ServiceAccountSummary, + key: Option, + }, + KeyRotated { + account: ServiceAccountSummary, + key: String, + }, + AccountSwitched { + account: ServiceAccountSummary, + disabled: bool, + }, + AccountsListed(Vec), } /// Parsing can finish an invocation before package discovery or any Python handoff. @@ -58,12 +170,21 @@ pub(crate) enum NativeParse { }, } -/// One turn of named work: the files it wrote, whether metadata should sync, and whether it claimed work. +/// One turn of named work: its files, whether to sync, whether it claimed, and any republish owed. #[derive(Debug, Default)] pub(crate) struct LocationWorkTurn { pub(crate) files: Vec, pub(crate) sync: bool, pub(crate) claimed: bool, + pub(crate) republish: Option, +} + +/// A claimed republish: its result is reported after the next compile, before its lease ends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PendingRepublish { + pub(crate) request_id: uuid::Uuid, + pub(crate) claim_id: uuid::Uuid, + pub(crate) deadline: tokio::time::Instant, } /// What `sqb skills` installs. @@ -173,6 +294,8 @@ pub(crate) struct DevControlState { /// `None` until `sqb dev` reports its foreground connection; outside `sqb dev`, always connected. pub(crate) warehouse: Option, pub(crate) recompiles: u64, + /// How many of those recompiles also call every discover function again, as `r` and the republish API do. + pub(crate) rediscovers: u64, } /// Retained source observations survive compilation; warehouse exclusions never replace them. @@ -180,6 +303,8 @@ pub(crate) struct DevControlState { pub(crate) struct LocationWatch { pub(crate) rules: SnapshotRules, pub(crate) local_files: Vec, + /// `sqb dev`'s run output folder where it lies inside the project, left out with everything beneath it. + pub(crate) output_folders: Vec, pub(crate) observed: (Vec, Option), pub(crate) attempted: Option<(Vec, Option)>, pub(crate) changed_at: tokio::time::Instant, @@ -188,6 +313,18 @@ pub(crate) struct LocationWatch { pub(crate) commit_checked_at: tokio::time::Instant, /// Whether a generation has published, so the next publication's connection check is not the startup check. pub(crate) checked: bool, + /// A claimed republish, owed the result of the next compile to finish. + pub(crate) republish: Option, +} + +/// What one compile published, for the watcher and any republish it owes. +#[derive(Debug)] +pub(crate) struct LoadedGeneration { + pub(crate) refresh_at: Option, + pub(crate) state_locations: + Vec, + pub(crate) secrets: crate::native_commands::types::GenerationSecrets, + pub(crate) snapshot_id: uuid::Uuid, } /// A bounded supervisor request; dropping the reply cancels and reaps an active compiler. @@ -203,6 +340,12 @@ pub(crate) struct LocationCompileRequest { pub(crate) struct LocationLoad { pub(crate) published: Option, pub(crate) rules: Option, + /// The discovered sets the compile used; empty in a project without discover functions. + pub(crate) discovered: sqlbuild_orchestration::discovered_sets::types::DiscoveredSets, + /// Each discover function's file, relative to the project. + pub(crate) discover_files: std::collections::BTreeMap, + /// Why nothing was published, redacted; null after a publication or a rules failure. + pub(crate) error: Option, } /// A `{"plan": {"argv", "copy"}}` request for the runtime interpreter, answered with its reply. @@ -655,3 +798,52 @@ pub(crate) struct SensorTrialArguments { pub(crate) choice: SensorEventChoice, pub(crate) source: EventSource, } + +/// Never prints an imported key, so a debug log can't leak it. +impl std::fmt::Debug for ServiceAccountAdmin { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Create { request, key } => formatter + .debug_struct("Create") + .field("request", request) + .field("key", &key.as_ref().map(|_| "[redacted]")) + .finish(), + Self::Rotate { + name, + overlap_minutes, + } => formatter + .debug_struct("Rotate") + .field("name", name) + .field("overlap_minutes", overlap_minutes) + .finish(), + Self::SetDisabled { name, disabled } => formatter + .debug_struct("SetDisabled") + .field("name", name) + .field("disabled", disabled) + .finish(), + Self::List => formatter.write_str("List"), + } + } +} + +/// Who a republish is requested as; the key never appears in diagnostics. +pub(crate) enum RepublishCaller { + Key { server: String, key: String }, + Session { server: String, ca: Option }, +} + +impl std::fmt::Debug for RepublishCaller { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Key { server, .. } => formatter + .debug_struct("Key") + .field("server", server) + .finish_non_exhaustive(), + Self::Session { server, ca } => formatter + .debug_struct("Session") + .field("server", server) + .field("ca", ca) + .finish(), + } + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests.rs b/crates/sqlbuild-cli/src/native_commands/tests.rs index 021c851fc7..612025842f 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests.rs @@ -1,3 +1,5 @@ +#[path = "tests/test_admin_output.rs"] +mod admin_output; #[path = "tests/test_argv_host.rs"] mod argv_host; #[path = "tests/test_changed_build.rs"] @@ -8,6 +10,8 @@ mod decision; mod helpers; #[path = "tests/test_init.rs"] mod init; +#[path = "tests/test_location_discovery.rs"] +mod location_discovery; #[path = "tests/test_location_metadata.rs"] mod location_metadata; #[path = "tests/test_location_plan.rs"] diff --git a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs index 54fd72e4d4..25f3934a60 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs @@ -1,3 +1,4 @@ +use sqlbuild_orchestration::platform::models::LocationWorkScope; use std::path::Path; use std::sync::Mutex; @@ -144,6 +145,7 @@ pub(super) fn republished_location( let poll = LocationWorkPoll { session_id: Uuid::nil(), target: options.target.clone(), + scope: LocationWorkScope::All, }; let (_, metadata, _) = tokio::runtime::Builder::new_current_thread() .enable_all() @@ -222,3 +224,107 @@ pub(super) fn kept_plans(count: usize, limits: (usize, usize)) -> Mutex Vec { + paths + .iter() + .map(|path| sqlbuild_cache::project_snapshot::models::PathStamp { + relative_path: (*path).to_owned(), + kind: "file", + size: 1 + u64::from(edited.contains(path)), + mtime_ns: 0, + ctime_ns: 0, + inode: 0, + link: None, + }) + .collect() +} + +/// A published load whose `orders_plan`, checked every 15 minutes and defined in `PLAN_FILE`, has `ids`. +pub(super) fn discovered_load(ids: &[&str]) -> crate::native_commands::models::LocationLoad { + use sqlbuild_orchestration::discovered_sets::main::record_attempt::record_attempt; + use sqlbuild_orchestration::discovered_sets::models::{DiscoveredItem, DiscoveredResult}; + let at: DateTime = Utc + .with_ymd_and_hms(2026, 11, 21, 9, 0, 0) + .single() + .expect("a valid time"); + let result = DiscoveredResult { + items: ids + .iter() + .map(|id| DiscoveredItem { + id: (*id).to_owned(), + depends_on: Vec::new(), + args: std::collections::BTreeMap::new(), + }) + .collect(), + tags: std::collections::BTreeMap::new(), + max_parallel: None, + }; + let record = sqlbuild_orchestration::snapshots::models::SnapshotRecord { + snapshot_id: Uuid::nil(), + location_id: Uuid::nil(), + target: "dev".to_owned(), + generation: 1, + manifest_digest: String::new(), + published_at: at, + }; + crate::native_commands::models::LocationLoad { + published: Some( + sqlbuild_orchestration::platform::models::PublishedGeneration { + record, + refresh_at: None, + state_locations: Vec::new(), + missing_secrets: Vec::new(), + secrets_needed_by: std::collections::BTreeMap::new(), + }, + ), + rules: None, + discovered: [( + "orders_plan".to_owned(), + record_attempt(None, Ok(result), (at, Some(900))), + )] + .into(), + discover_files: [("orders_plan".to_owned(), PLAN_FILE.to_owned())].into(), + error: None, + } +} + +/// The reply of a compile that failed, with the sets it had discovered by then, if any. +pub(super) fn failed_load(discovered: bool) -> crate::native_commands::models::LocationLoad { + let mut load = discovered_load(&["a"]); + load.published = None; + load.discover_files.clear(); + load.discovered.retain(|_, _| discovered); + load +} + +/// An interpreter that reads nothing and never replies. +#[cfg(unix)] +pub(super) fn silent_compiler() -> crate::native_commands::models::LocationCompiler { + scripted_compiler("exec sleep 600") +} + +/// An interpreter that runs `script` in place of answering. +#[cfg(unix)] +pub(super) fn scripted_compiler(script: &str) -> crate::native_commands::models::LocationCompiler { + let mut child = tokio::process::Command::new("sh") + .args(["-c", script]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .kill_on_drop(true) + .spawn() + .expect("silent interpreter"); + crate::native_commands::models::LocationCompiler { + stdin: child.stdin.take().expect("interpreter input"), + stdout: tokio::io::BufReader::new(child.stdout.take().expect("interpreter output")), + child, + python_sources: Vec::new(), + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_admin_output.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_admin_output.rs new file mode 100644 index 0000000000..aa7b84e6de --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_admin_output.rs @@ -0,0 +1,241 @@ +//! Admin results that need a published project to produce still name what was done. + +use sqlbuild_orchestration::declarations::models::TriggerChange; +use uuid::Uuid; + +use crate::native_commands::_helpers::admin::{rows::stdout_text, summaries::summary_line}; +use crate::native_commands::models::AdminDone; +use crate::native_commands::tests::test_types::AdminTextTestCase; + +#[test] +fn given_an_admin_result_when_printed_without_json_then_one_line_names_what_was_done() { + let [run, source, event] = [10, 11, 12].map(Uuid::from_u128); + let test_cases = [ + AdminTextTestCase { + description: "the first admin", + done: AdminDone::Bootstrapped { + id: run, + name: "ada".to_owned(), + }, + expected_line: Some("Created admin user ada (00000000-0000-0000-0000-00000000000a)"), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a queued job run", + done: AdminDone::RunQueued { + run_id: run, + job: "nightly_job".to_owned(), + target: "production".to_owned(), + applied: true, + }, + expected_line: Some( + "Queued a run of nightly_job on target production (00000000-0000-0000-0000-00000000000a)", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a repeated job run", + done: AdminDone::RunQueued { + run_id: run, + job: "nightly_job".to_owned(), + target: "production".to_owned(), + applied: false, + }, + expected_line: Some( + "Run 00000000-0000-0000-0000-00000000000a was already requested; nothing changed", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a queued rerun", + done: AdminDone::RerunQueued { + run_id: run, + source, + applied: true, + }, + expected_line: Some( + "Queued a rerun of run 00000000-0000-0000-0000-00000000000b (00000000-0000-0000-0000-00000000000a)", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a repeated rerun", + done: AdminDone::RerunQueued { + run_id: run, + source, + applied: false, + }, + expected_line: Some( + "Run 00000000-0000-0000-0000-00000000000a was already requested; nothing changed", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a connection check", + done: AdminDone::CheckRequested { + request_id: run, + location: "orders".to_owned(), + target: "production".to_owned(), + applied: true, + }, + expected_line: Some( + "Requested a connection check of orders on target production (00000000-0000-0000-0000-00000000000a)", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a repeated check", + done: AdminDone::CheckRequested { + request_id: run, + location: "orders".to_owned(), + target: "production".to_owned(), + applied: false, + }, + expected_line: Some( + "Connection check 00000000-0000-0000-0000-00000000000a was already requested; nothing changed", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a cancellation", + done: AdminDone::CancelRequested { + event_id: event, + run_id: run, + applied: true, + }, + expected_line: Some( + "Requested cancellation of run 00000000-0000-0000-0000-00000000000a (00000000-0000-0000-0000-00000000000c)", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a repeated cancellation", + done: AdminDone::CancelRequested { + event_id: event, + run_id: run, + applied: false, + }, + expected_line: Some( + "Cancellation of run 00000000-0000-0000-0000-00000000000a (00000000-0000-0000-0000-00000000000c) was already requested; nothing changed", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "an enabled trigger", + done: AdminDone::TriggerChanged { + event_id: event, + trigger_id: run, + change: TriggerChange::Enable, + applied: true, + }, + expected_line: Some("Enabled trigger 00000000-0000-0000-0000-00000000000a"), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a paused trigger", + done: AdminDone::TriggerChanged { + event_id: event, + trigger_id: run, + change: TriggerChange::Pause, + applied: true, + }, + expected_line: Some("Paused trigger 00000000-0000-0000-0000-00000000000a"), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a default status", + done: AdminDone::TriggerChanged { + event_id: event, + trigger_id: run, + change: TriggerChange::ResetDefault, + applied: true, + }, + expected_line: Some( + "Reset trigger 00000000-0000-0000-0000-00000000000a to its default status", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a set cursor", + done: AdminDone::TriggerChanged { + event_id: event, + trigger_id: run, + change: TriggerChange::SetCursor { + time: chrono::DateTime::UNIX_EPOCH, + }, + applied: true, + }, + expected_line: Some( + "Set the cursor of trigger 00000000-0000-0000-0000-00000000000a to 1970-01-01T00:00:00Z", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a reset cursor", + done: AdminDone::TriggerChanged { + event_id: event, + trigger_id: run, + change: TriggerChange::ResetCursor, + applied: true, + }, + expected_line: Some("Reset the cursor of trigger 00000000-0000-0000-0000-00000000000a"), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a skipped event", + done: AdminDone::TriggerChanged { + event_id: event, + trigger_id: run, + change: TriggerChange::SkipEvent { + event: "orders-17".to_owned(), + }, + applied: true, + }, + expected_line: Some( + "Skipped event orders-17 of trigger 00000000-0000-0000-0000-00000000000a", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a repeated change", + done: AdminDone::TriggerChanged { + event_id: event, + trigger_id: run, + change: TriggerChange::Pause, + applied: false, + }, + expected_line: Some( + "The change to trigger 00000000-0000-0000-0000-00000000000a (00000000-0000-0000-0000-00000000000c) was already made; nothing changed", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "a token revoked before", + done: AdminDone::TokenRevoked { + id: run, + revoked: false, + }, + expected_line: Some( + "Token 00000000-0000-0000-0000-00000000000a was already revoked or doesn't exist; nothing changed", + ), + expected_stdout: "", + }, + AdminTextTestCase { + description: "no service accounts", + done: AdminDone::AccountsListed(Vec::new()), + expected_line: Some("No service accounts"), + expected_stdout: "", + }, + ]; + for test_case in test_cases { + assert_eq!( + (summary_line(&test_case.done), stdout_text(&test_case.done)), + ( + test_case.expected_line.map(str::to_owned), + test_case.expected_stdout.to_owned(), + ), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_location_discovery.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_location_discovery.rs new file mode 100644 index 0000000000..7ddfa67821 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_location_discovery.rs @@ -0,0 +1,379 @@ +use std::time::Duration; + +use sqlbuild_cache::project_snapshot::models::PathStamp; +use sqlbuild_orchestration::discovered_sets::models::DiscoveredSetChecked; +use tokio::time::Instant; + +#[cfg(unix)] +use crate::native_commands::_helpers::location::compiler_discovery::check_discovered; +use crate::native_commands::_helpers::location::discovery_state::LocationDiscovery; +#[cfg(unix)] +use crate::native_commands::models::{LocationCompileRequest, LocationRuntimeRequest}; +use crate::native_commands::tests::helpers::{PLAN_FILE, discovered_load, failed_load, stamps}; +#[cfg(unix)] +use crate::native_commands::tests::helpers::{scripted_compiler, silent_compiler}; +#[cfg(unix)] +use crate::native_commands::tests::test_types::{CheckGraceTestCase, CheckShutdownTestCase}; +use crate::native_commands::tests::test_types::{ + DiscoveryCheckTestCase, DiscoveryReportTestCase, FailedCompileDiscoveryTestCase, + RediscoverTestCase, +}; + +const OTHER_FILE: &str = "python/assets/other.py"; +const FIFTEEN_MINUTES: Duration = Duration::from_secs(900); + +#[test] +fn given_a_published_location_when_it_publishes_again_then_only_edited_discover_modules_run_again() +{ + let test_cases = [ + RediscoverTestCase { + description: "a SQL or unrelated edit reuses every set", + changed: &[OTHER_FILE], + everything: false, + expected_rediscover: Some(&[]), + }, + RediscoverTestCase { + description: "an edit to the discover function's own module runs it again", + changed: &[PLAN_FILE], + everything: false, + expected_rediscover: Some(&["orders_plan"]), + }, + RediscoverTestCase { + description: "r and the republish API discover everything", + changed: &[], + everything: true, + expected_rediscover: None, + }, + ]; + let before: Vec = stamps(&[PLAN_FILE, OTHER_FILE], &[]); + + for test_case in test_cases { + let mut discovery = LocationDiscovery::default(); + let first = discovery.publish_request(1, (&[], &before), 0); + discovery.published(&discovered_load(&["a"]), Instant::now()); + let after: Vec = stamps(&[PLAN_FILE, OTHER_FILE], test_case.changed); + let next = discovery.publish_request(2, (&before, &after), u64::from(test_case.everything)); + let rediscover: Option> = + next.rediscover.map(|names| names.into_iter().collect()); + + assert_eq!( + ( + first.rediscover.is_none(), + first.seed, + rediscover, + next.seed + ), + ( + true, + true, + test_case + .expected_rediscover + .map(|names| names.iter().map(|name| (*name).to_owned()).collect()), + false + ), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_set_checked_every_15_minutes_when_its_check_finds_new_items_then_the_next_publication_reuses_them() + { + let test_cases = [ + DiscoveryCheckTestCase { + description: "a changed result is kept for the next publication", + checked_ids: &["a", "b"], + changed: true, + expected_early_check: false, + expected_republish: true, + expected_ids: &["a", "b"], + }, + DiscoveryCheckTestCase { + description: "an unchanged result keeps the published items", + checked_ids: &["a"], + changed: false, + expected_early_check: false, + expected_republish: false, + expected_ids: &["a"], + }, + ]; + let start = Instant::now(); + + for test_case in test_cases { + let mut discovery = LocationDiscovery::default(); + discovery.published(&discovered_load(&["a"]), start); + let early: bool = discovery.due_check(start).is_some(); + let fresh = discovered_load(test_case.checked_ids).discovered["orders_plan"].clone(); + let republish = discovery.checked( + "orders_plan", + DiscoveredSetChecked { + set: Some(fresh), + changed: test_case.changed, + }, + start + FIFTEEN_MINUTES, + ); + let next = discovery.publish_request(2, (&[], &[]), 0); + let ids: Vec<&str> = next.previous["orders_plan"] + .result + .iter() + .flat_map(|result| &result.items) + .map(|item| item.id.as_str()) + .collect(); + + assert_eq!( + (early, republish, ids), + ( + test_case.expected_early_check, + test_case.expected_republish, + test_case.expected_ids.to_vec() + ), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_failed_compile_when_the_location_retries_then_it_still_discovers_what_was_asked_for() { + let test_cases = [ + FailedCompileDiscoveryTestCase { + description: "an edit whose compile failed before discovery", + edited_before_failure: &[PLAN_FILE], + edited_after_failure: &[], + everything: false, + discovered_before_failing: false, + expected_rediscover: Some(&["orders_plan"]), + }, + FailedCompileDiscoveryTestCase { + description: "an edit after a compile that failed following discovery", + edited_before_failure: &[], + edited_after_failure: &[PLAN_FILE], + everything: false, + discovered_before_failing: true, + expected_rediscover: Some(&["orders_plan"]), + }, + FailedCompileDiscoveryTestCase { + description: "r whose compile failed", + edited_before_failure: &[], + edited_after_failure: &[], + everything: true, + discovered_before_failing: false, + expected_rediscover: None, + }, + ]; + let before: Vec = stamps(&[PLAN_FILE], &[]); + + for test_case in test_cases { + let asked: u64 = u64::from(test_case.everything); + let failing: Vec = stamps(&[PLAN_FILE], test_case.edited_before_failure); + let edited: [&[&str]; 2] = [ + test_case.edited_before_failure, + test_case.edited_after_failure, + ]; + let retried: Vec = stamps(&[PLAN_FILE], &edited.concat()); + let mut discovery = LocationDiscovery::default(); + discovery.publish_request(1, (&[], &before), 0); + discovery.published(&discovered_load(&["a"]), Instant::now()); + discovery.publish_request(2, (&before, &failing), asked); + discovery.published( + &failed_load(test_case.discovered_before_failing), + Instant::now(), + ); + let rediscover: Option> = discovery + .publish_request(3, (&failing, &retried), asked) + .rediscover + .map(|names| names.into_iter().collect()); + + assert_eq!( + rediscover, + test_case + .expected_rediscover + .map(|names| names.iter().map(|name| (*name).to_owned()).collect()), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_second_publication_when_reporting_sets_then_removing_the_last_one_clears_its_health() { + let test_cases = [ + DiscoveryReportTestCase { + description: "sets are reported", + had_sets: true, + has_sets: true, + expected_report: true, + }, + DiscoveryReportTestCase { + description: "removing the last set reports none", + had_sets: true, + has_sets: false, + expected_report: true, + }, + DiscoveryReportTestCase { + description: "a project without sets stays quiet", + had_sets: false, + has_sets: false, + expected_report: false, + }, + ]; + + for test_case in test_cases { + let mut first = discovered_load(&["a"]); + first.discovered.retain(|_, _| test_case.had_sets); + let mut second = discovered_load(&["a"]); + second.discovered.retain(|_, _| test_case.has_sets); + let mut discovery = LocationDiscovery::default(); + discovery.published(&first, Instant::now()); + + assert_eq!( + discovery.reports(&second), + test_case.expected_report, + "{}", + test_case.description + ); + } +} + +#[cfg(unix)] +#[test] +fn given_a_check_that_never_returns_when_the_location_shuts_down_then_the_check_ends_promptly() { + let test_cases = [ + CheckShutdownTestCase { + description: "shutdown before the check starts", + closes_after: Duration::ZERO, + expected_within: Duration::from_secs(5), + expected_compiler: false, + }, + CheckShutdownTestCase { + description: "shutdown during the check", + closes_after: Duration::from_millis(300), + expected_within: Duration::from_secs(5), + expected_compiler: false, + }, + ]; + + for test_case in test_cases { + let kept: bool = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(async { + let mut load = discovered_load(&["a"]); + for set in load.discovered.values_mut() { + set.check_every_seconds = Some(0); + } + let mut discovery = LocationDiscovery::default(); + discovery.published(&load, Instant::now()); + let (republish, _controls) = tokio::sync::watch::channel(Default::default()); + let (sender, requests) = tokio::sync::mpsc::channel(1); + let check = check_discovered( + Some(silent_compiler()), + &mut discovery, + ((&republish, ("synthetic", uuid::Uuid::nil())), &requests), + ); + let shutdown = async { + tokio::time::sleep(test_case.closes_after).await; + drop(sender); + }; + tokio::time::timeout(test_case.expected_within, async { + tokio::join!(check, shutdown).0 + }) + .await + .expect("the check ends promptly") + .expect("the interpreter stops") + .is_some() + }); + + assert_eq!( + kept, test_case.expected_compiler, + "{}", + test_case.description + ); + } +} + +#[cfg(unix)] +#[test] +fn given_a_request_waiting_on_a_check_when_the_grace_passes_then_only_an_unfinished_check_is_abandoned() + { + let test_cases = [ + CheckGraceTestCase { + description: "a check that never returns is abandoned after 10 seconds", + script: "exec sleep 600", + waiting: 1, + expected_at_least: Duration::from_secs(10), + expected_within: Duration::from_secs(15), + expected_compiler: false, + }, + CheckGraceTestCase { + description: "a check that finishes inside the 10 seconds is kept", + script: r#"read request; sleep 2; echo '{"set":null,"changed":false}'; exec sleep 600"#, + waiting: 1, + expected_at_least: Duration::from_secs(2), + expected_within: Duration::from_secs(9), + expected_compiler: true, + }, + CheckGraceTestCase { + description: "a slower check nothing waits for is kept", + script: r#"read request; sleep 11; echo '{"set":null,"changed":false}'; exec sleep 600"#, + waiting: 0, + expected_at_least: Duration::from_secs(11), + expected_within: Duration::from_secs(16), + expected_compiler: true, + }, + ]; + + for test_case in test_cases { + let (kept, elapsed): (bool, Duration) = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(async { + let mut load = discovered_load(&["a"]); + for set in load.discovered.values_mut() { + set.check_every_seconds = Some(0); + } + let mut discovery = LocationDiscovery::default(); + discovery.published(&load, Instant::now()); + let (republish, _controls) = tokio::sync::watch::channel(Default::default()); + let (sender, requests) = tokio::sync::mpsc::channel(1); + for generation in 0..test_case.waiting { + let (reply, _) = tokio::sync::oneshot::channel(); + sender + .send(LocationRuntimeRequest::Publish(LocationCompileRequest { + generation: generation as i64, + python_sources: Vec::new(), + reply, + })) + .await + .expect("a request waits"); + } + let started = Instant::now(); + let compiler = tokio::time::timeout( + test_case.expected_within, + check_discovered( + Some(scripted_compiler(test_case.script)), + &mut discovery, + ((&republish, ("synthetic", uuid::Uuid::nil())), &requests), + ), + ) + .await + .expect("the check ends in time") + .expect("the interpreter is usable or stopped"); + (compiler.is_some(), started.elapsed()) + }); + + assert_eq!( + kept, test_case.expected_compiler, + "{}", + test_case.description + ); + assert!( + elapsed >= test_case.expected_at_least, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs index a670a8cf8e..b4d78b0087 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs @@ -114,6 +114,7 @@ fn given_a_turn_of_location_work_when_scheduling_the_next_check_then_only_an_idl files: Vec::new(), sync: test_case.sync, claimed: test_case.claimed, + republish: None, }; assert_eq!( next_work_check(&turn, now) - now, diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_paths.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_paths.rs index 0719de5363..65e93e7a58 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_paths.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_paths.rs @@ -1,7 +1,13 @@ use std::path::{Path, PathBuf}; -use crate::native_commands::_helpers::command::paths::{pathlib_path, resolved_path}; -use crate::native_commands::tests::test_types::{PathlibTestCase, ResolveTestCase}; +use crate::native_commands::_helpers::command::paths::{ + location_files, location_output_folders, location_watch, pathlib_path, resolved_path, +}; +use crate::native_commands::models::LocationWatch; +use crate::native_commands::tests::helpers::write_tree; +use crate::native_commands::tests::test_types::{ + OutputWatchTestCase, PathlibTestCase, ResolveTestCase, +}; #[test] fn given_project_dir_text_when_building_a_path_then_pathlib_normalisation_applies() { @@ -75,3 +81,115 @@ fn given_relative_path_when_resolving_then_existing_prefix_is_real_and_rest_is_k ); } } + +#[test] +fn given_a_dev_run_output_folder_when_a_file_is_written_then_the_watch_leaves_out_only_that_folder() +{ + let test_cases = [ + OutputWatchTestCase { + description: "run output in the resolved folder is not an edit", + folder: Some("output"), + written: "output/runs/run/claim/000000000000.zst", + expected_seen: false, + }, + OutputWatchTestCase { + description: "run output in a nested store folder is not an edit", + folder: Some("state/output"), + written: "state/output/runs/run/claim/000000000000.zst", + expected_seen: false, + }, + OutputWatchTestCase { + description: "a folder given through a parent reference is resolved", + folder: Some("models/../output"), + written: "output/runs/run/claim/000000000000.zst", + expected_seen: false, + }, + OutputWatchTestCase { + description: "a source edit beside the folder is seen", + folder: Some("output"), + written: "models/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "the folder's parent is still watched", + folder: Some("state/output"), + written: "state/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "another folder named output is still watched", + folder: Some("output"), + written: "models/output/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "a folder whose name starts with output is still watched", + folder: Some("output"), + written: "output_models/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "a store at the project root leaves the watch on", + folder: Some("."), + written: "models/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "a store resolving to the project root leaves the watch on", + folder: Some("models/.."), + written: "models/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "a store above the project leaves the watch on", + folder: Some(".."), + written: "models/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "a store outside the project excludes nothing inside it", + folder: Some("../elsewhere/output"), + written: "output/orders.sql", + expected_seen: true, + }, + OutputWatchTestCase { + description: "without a local store nothing more is left out", + folder: None, + written: "output/orders.sql", + expected_seen: true, + }, + ]; + + for test_case in test_cases { + let directory = tempfile::tempdir().expect("temporary directory"); + // sqb dev creates the store's folder before its location starts watching. + write_tree( + directory.path(), + &["project/models", "project/state"], + &[("project/models/orders.sql", "select 1")], + ); + let root: PathBuf = + std::fs::canonicalize(directory.path().join("project")).expect("real project"); + let folder: Option = test_case.folder.map(|folder| root.join(folder)); + let mut watch: LocationWatch = location_watch(&root); + watch.output_folders = location_output_folders(&root, folder.as_deref()); + let files = || { + location_files( + &root, + &watch.rules, + (&watch.local_files, &watch.output_folders), + ) + }; + let before = files(); + let written: PathBuf = root.join(test_case.written); + std::fs::create_dir_all(written.parent().expect("parent")).expect("create parent"); + std::fs::write(&written, "select 2 as order_id").expect("write file"); + + assert_eq!( + files() != before, + test_case.expected_seen, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_provider_secrets.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_provider_secrets.rs index 6737ce2cb7..b9cd9644e4 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_provider_secrets.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_provider_secrets.rs @@ -53,15 +53,23 @@ fn given_providers_missing_secrets_when_the_dev_warning_is_built_then_allowed_pr allowed: *allowed, }) .collect(); - let unset: Vec<(String, Vec)> = unset_provider_secrets(&providers) - .into_iter() - .map( - |UnsetProviderSecrets { - provider, - variables, - }| (provider, variables), - ) - .collect(); + let unset: Vec<(String, Vec)> = + unset_provider_secrets(&providers, &std::collections::BTreeMap::new()) + .into_iter() + .map( + |UnsetProviderSecrets { + provider, settings, .. + }| { + ( + provider, + settings + .into_iter() + .map(|setting| setting.variable) + .collect(), + ) + }, + ) + .collect(); assert_eq!( unset, diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs index 12950ddca5..a933eb5764 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs @@ -42,6 +42,14 @@ pub(super) struct ResolveTestCase { pub(super) expected_parts: &'static [&'static str], } +/// `sqb dev`'s run output folder from the project, a file written afterwards and whether the watch sees it. +pub(super) struct OutputWatchTestCase { + pub(super) description: &'static str, + pub(super) folder: Option<&'static str>, + pub(super) written: &'static str, + pub(super) expected_seen: bool, +} + /// Project directories and files, and whether an observed command can run without Python. pub(super) struct ProjectFactsTestCase { pub(super) description: &'static str, @@ -404,3 +412,71 @@ pub(super) struct UnsetProviderSecretsTestCase { pub(super) providers: Vec<(&'static str, bool, Vec<&'static str>)>, pub(super) expected_unset: Vec<(&'static str, Vec<&'static str>)>, } + +/// One admin result and what it prints without `--json`. +pub(crate) struct AdminTextTestCase { + pub(crate) description: &'static str, + pub(crate) done: crate::native_commands::models::AdminDone, + pub(crate) expected_line: Option<&'static str>, + pub(crate) expected_stdout: &'static str, +} + +/// A publication after a first one, and the discover functions the location calls again. +pub(super) struct RediscoverTestCase { + pub(super) description: &'static str, + /// The Python files whose stamps changed since the last publication. + pub(super) changed: &'static [&'static str], + /// Whether `r` or the republish API asked to discover everything. + pub(super) everything: bool, + /// `None` when every function is called again. + pub(super) expected_rediscover: Option<&'static [&'static str]>, +} + +/// A `check_every` check that finds new items, and what the next publication reuses. +pub(super) struct DiscoveryCheckTestCase { + pub(super) description: &'static str, + pub(super) checked_ids: &'static [&'static str], + pub(super) changed: bool, + pub(super) expected_early_check: bool, + pub(super) expected_republish: bool, + pub(super) expected_ids: &'static [&'static str], +} + +/// A failed compile between an edit or `r` and the next attempt, which must still discover it. +pub(super) struct FailedCompileDiscoveryTestCase { + pub(super) description: &'static str, + pub(super) edited_before_failure: &'static [&'static str], + pub(super) edited_after_failure: &'static [&'static str], + pub(super) everything: bool, + /// Whether the failure came after discovery ran, so the runtime reported sets without files. + pub(super) discovered_before_failing: bool, + pub(super) expected_rediscover: Option<&'static [&'static str]>, +} + +/// A second publication, and whether the location reports its discovered sets. +pub(super) struct DiscoveryReportTestCase { + pub(super) description: &'static str, + pub(super) had_sets: bool, + pub(super) has_sets: bool, + pub(super) expected_report: bool, +} + +/// A `check_every` check that never answers, and when shutdown closes the compiler's requests. +#[cfg(unix)] +pub(super) struct CheckShutdownTestCase { + pub(super) description: &'static str, + pub(super) closes_after: std::time::Duration, + pub(super) expected_within: std::time::Duration, + pub(super) expected_compiler: bool, +} + +#[cfg(unix)] +pub(super) struct CheckGraceTestCase { + pub(super) description: &'static str, + pub(super) script: &'static str, + /// How many requests wait while the check runs. + pub(super) waiting: usize, + pub(super) expected_at_least: std::time::Duration, + pub(super) expected_within: std::time::Duration, + pub(super) expected_compiler: bool, +} diff --git a/crates/sqlbuild-cli/src/native_commands/types.rs b/crates/sqlbuild-cli/src/native_commands/types.rs index 6bbb77e3a6..c3ce30e98b 100644 --- a/crates/sqlbuild-cli/src/native_commands/types.rs +++ b/crates/sqlbuild-cli/src/native_commands/types.rs @@ -1,6 +1,6 @@ //! Private interpreter protocol shapes owned by the location supervisor. -use crate::native_commands::models::{LocationMetadataSync, LocationWatch}; +use crate::native_commands::models::{LoadedGeneration, LocationMetadataSync, LocationWatch}; use sqlbuild_orchestration::platform::models::{LocationRuleFailure, MissingProviderSecrets}; use sqlbuild_orchestration::warehouse_metadata::models::WarehouseStateLocation; @@ -18,15 +18,14 @@ pub(crate) type NextGeneration = ( Option>, ); -/// A published generation's refresh deadline, state locations and providers missing secrets, or the rule findings that failed it. -pub(crate) type LoadOutcome = Result< - ( - Option, - Vec, - Vec, - ), - Option, ->; +/// The providers a generation shows missing secrets, and the node keys that need each. +pub(crate) type GenerationSecrets = ( + Vec, + std::collections::BTreeMap>, +); + +/// A compile's publication; or any rule findings and the error. +pub(crate) type LoadOutcome = Result, String)>; /// A plan document and the model diffs it left out, by model, which the server stores apart. pub(crate) type LocationPlan = ( @@ -45,3 +44,9 @@ pub(crate) type PlanSettings<'a> = ( &'a std::collections::BTreeMap, &'a std::collections::BTreeSet, ); + +/// The republish trigger and the location's credential and session, for discovery's checks and health. +pub(crate) type DiscoveryControls<'a> = ( + &'a tokio::sync::watch::Sender, + (&'a str, uuid::Uuid), +); diff --git a/crates/sqlbuild-cli/src/person_login/_helpers/flow.rs b/crates/sqlbuild-cli/src/person_login/_helpers/flow.rs index 2bc05bedc4..28139a916c 100644 --- a/crates/sqlbuild-cli/src/person_login/_helpers/flow.rs +++ b/crates/sqlbuild-cli/src/person_login/_helpers/flow.rs @@ -7,7 +7,7 @@ use chrono::Utc; use serde_json::json; use sqlbuild_recall::records::main::sha256_hex::sha256_hex; -use crate::person_login::constants::{LOGIN_SECONDS, POLL_SECONDS, SECRET_BYTES}; +use crate::person_login::constants::{KEYS_ONLY_MODE, LOGIN_SECONDS, POLL_SECONDS, SECRET_BYTES}; use crate::person_login::main::open_browser::open_browser; use crate::person_login::models::{LoginFlow, PersonClient, PersonCredential}; @@ -30,6 +30,11 @@ pub(crate) async fn login( .send() .await .map_err(|_| std::io::Error::other("could not start browser sign-in"))?; + if response.status() == reqwest::StatusCode::NOT_FOUND && keys_only(client).await { + return Err(std::io::Error::other( + "this server has no sign-in for people: scripts call it with a service account key", + )); + } if !response.status().is_success() { return Err(std::io::Error::other( "server rejected CLI sign-in; check its authentication configuration or wait before retrying", @@ -89,3 +94,17 @@ pub(crate) async fn login( "CLI sign-in expired; start sqb login again", )) } + +/// Whether the server answers that only service account keys call it. +async fn keys_only(client: &PersonClient) -> bool { + let Ok(response) = client + .client + .get(format!("{}/api/auth/login-mode", client.origin)) + .send() + .await + else { + return false; + }; + let answer: serde_json::Value = response.json().await.unwrap_or_default(); + answer["login_mode"] == KEYS_ONLY_MODE +} diff --git a/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs b/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs index 961c124caf..6500164f19 100644 --- a/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs +++ b/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs @@ -7,7 +7,7 @@ use reqwest::header::{AUTHORIZATION, HeaderValue}; use sqlbuild_orchestration::api::main::parse_origin::parse_origin; use sqlbuild_orchestration::api::models::{ApiErrorBody, MutationResponse}; use sqlbuild_orchestration::credentials::models::SessionIdentity; -use sqlbuild_orchestration::platform::models::PersonWorkRequest; +use sqlbuild_orchestration::platform::models::{PersonWorkRequest, RepublishCall, RepublishStatus}; use sqlbuild_orchestration::sensors::models::{SensorEventChoice, SensorTrialEvents}; use sqlbuild_orchestration::snapshots::models::NodeSql; use uuid::Uuid; @@ -159,6 +159,28 @@ pub(crate) async fn warehouse_sync( .map(|response| response.applied) } +/// The republish after `call`; `None` when there is no such request. +pub(crate) async fn republish( + client: &PersonClient, + credential: &PersonCredential, + scope: (Uuid, &str), + call: RepublishCall<'_>, +) -> Result, std::io::Error> { + let (request, action) = match call { + RepublishCall::Request(request) => { + let path = target_path(client, scope, &["republish"])?; + let posted = authorized(client, reqwest::Method::POST, &path, credential)?; + (posted.json(request), "request a republish from") + } + RepublishCall::Read { request_id, wait } => { + let path = target_path(client, scope, &["republish", &request_id.to_string()])?; + let read = authorized(client, reqwest::Method::GET, &path, credential)?; + (read.query(&[("wait", wait)]), "read the republish from") + } + }; + send_json(request, (action, "Republish request", "republish status")).await +} + /// The published sensor and the events `choice` picks; a refusal carries the server's reason. pub(crate) async fn sensor_events( client: &PersonClient, diff --git a/crates/sqlbuild-cli/src/person_login/constants.rs b/crates/sqlbuild-cli/src/person_login/constants.rs index 5b55c33035..4d86eb4800 100644 --- a/crates/sqlbuild-cli/src/person_login/constants.rs +++ b/crates/sqlbuild-cli/src/person_login/constants.rs @@ -11,3 +11,6 @@ pub(super) const CONTROL_LOCATION_ENV: &str = "SQLBUILD_CONTROL_LOCATION"; pub(super) const CONTROL_CA_CERT_ENV: &str = "SQLBUILD_CONTROL_CA_CERT"; /// A post-build sync request gives up after this long so the build's exit is never held. pub(super) const BUILD_SYNC_SECONDS: u64 = 5; + +/// The login mode a server without sign-in for people reports. +pub(super) const KEYS_ONLY_MODE: &str = "keys"; diff --git a/crates/sqlbuild-cli/src/person_login/main/call_republish.rs b/crates/sqlbuild-cli/src/person_login/main/call_republish.rs new file mode 100644 index 0000000000..3aa70f160a --- /dev/null +++ b/crates/sqlbuild-cli/src/person_login/main/call_republish.rs @@ -0,0 +1,18 @@ +//! A saved person session asks for a republish or reads one back; the server checks the permission. + +use std::path::Path; + +use sqlbuild_orchestration::platform::models::{RepublishCall, RepublishStatus}; +use uuid::Uuid; + +use crate::person_login::_helpers::transport; + +pub(crate) fn call_republish( + server: (&str, Option<&Path>), + scope: (Uuid, &str), + call: RepublishCall<'_>, +) -> Result, std::io::Error> { + transport::with_person_session(server, async |client, credential| { + transport::republish(client, credential, scope, call).await + }) +} diff --git a/crates/sqlbuild-cli/src/person_login/main/mod.rs b/crates/sqlbuild-cli/src/person_login/main/mod.rs index 94767ec95b..bbdf074733 100644 --- a/crates/sqlbuild-cli/src/person_login/main/mod.rs +++ b/crates/sqlbuild-cli/src/person_login/main/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod call_republish; pub(crate) mod open_browser; pub(crate) mod read_node_sql; pub(crate) mod read_sensor_events; diff --git a/crates/sqlbuild-cli/src/server_config/constants.rs b/crates/sqlbuild-cli/src/server_config/constants.rs index 92f703b757..8c7b151af8 100644 --- a/crates/sqlbuild-cli/src/server_config/constants.rs +++ b/crates/sqlbuild-cli/src/server_config/constants.rs @@ -13,3 +13,17 @@ pub(super) const REPLACED_SERVER_FLAGS: [(&str, &str, &str); 3] = [ "[trusted_proxy]", ), ]; + +/// Units `[output] max_bytes_per_run` accepts, with the bytes each stands for. +pub(crate) const BYTE_UNITS: [(&str, u64); 10] = [ + ("", 1), + ("B", 1), + ("kB", 1_000), + ("MB", 1_000_000), + ("GB", 1_000_000_000), + ("TB", 1_000_000_000_000), + ("KiB", 1 << 10), + ("MiB", 1 << 20), + ("GiB", 1 << 30), + ("TiB", 1 << 40), +]; diff --git a/crates/sqlbuild-cli/src/server_config/mod.rs b/crates/sqlbuild-cli/src/server_config/mod.rs index 8ce3540380..000b5d83b3 100644 --- a/crates/sqlbuild-cli/src/server_config/mod.rs +++ b/crates/sqlbuild-cli/src/server_config/mod.rs @@ -1,5 +1,5 @@ //! The installation's `server.toml`: listener, retention, sign-in and launchers, read once at start-up. -mod constants; +pub(crate) mod constants; pub(crate) mod main; pub(crate) mod models; diff --git a/crates/sqlbuild-cli/src/server_config/models.rs b/crates/sqlbuild-cli/src/server_config/models.rs index 7c3324439f..22ea9c8978 100644 --- a/crates/sqlbuild-cli/src/server_config/models.rs +++ b/crates/sqlbuild-cli/src/server_config/models.rs @@ -13,6 +13,8 @@ pub(crate) struct ServerConfig { pub(crate) server: ServerSection, #[serde(default)] pub(crate) retention: RetentionSection, + #[serde(default)] + pub(crate) output: OutputSection, pub(crate) oidc: Option, pub(crate) trusted_proxy: Option, #[serde(default)] @@ -42,4 +44,24 @@ pub(crate) struct RetentionSection { pub(crate) run_log_days: Option, pub(crate) run_log_count: Option, pub(crate) state_history_versions: Option, + /// Days a finished run's output stays in the output store; defaults to `run_log_days`. + pub(crate) run_output_days: Option, +} + +/// Where run output is kept and how much of one run is kept. +#[derive(Debug, Default, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct OutputSection { + /// `file:///path` or `s3://bucket/prefix`; by default `output` beside a SQLite control store. + pub(crate) store: Option, + /// Bytes, as a number or text such as `"20GB"`; past it a run keeps its first and last parts. + pub(crate) max_bytes_per_run: Option, +} + +/// A byte count written as a number or as text with a unit, such as `"500MB"` or `"2GiB"`. +#[derive(Debug, serde::Deserialize)] +#[serde(untagged)] +pub(crate) enum ByteCount { + Number(u64), + Text(String), } diff --git a/crates/sqlbuild-cli/tests/native_commands.rs b/crates/sqlbuild-cli/tests/native_commands.rs index dc4e620f9f..708495a108 100644 --- a/crates/sqlbuild-cli/tests/native_commands.rs +++ b/crates/sqlbuild-cli/tests/native_commands.rs @@ -2,16 +2,24 @@ mod admin_helpers; #[path = "native_commands/helpers.rs"] mod helpers; +#[path = "native_commands/republish/helpers.rs"] +mod republish_helpers; #[path = "native_commands/admin/test_admin.rs"] mod test_admin; #[path = "native_commands/test_control.rs"] mod test_control; #[path = "native_commands/test_location_health.rs"] mod test_location_health; +#[path = "native_commands/admin/test_output.rs"] +mod test_output; #[path = "native_commands/admin/test_passwords.rs"] mod test_passwords; #[path = "native_commands/test_proxy.rs"] mod test_proxy; +#[path = "native_commands/test_republish.rs"] +mod test_republish; +#[path = "native_commands/admin/test_service_accounts.rs"] +mod test_service_accounts; #[path = "native_commands/test_types.rs"] mod test_types; #[path = "native_commands/worker/test_worker.rs"] diff --git a/crates/sqlbuild-cli/tests/native_commands/admin/helpers.rs b/crates/sqlbuild-cli/tests/native_commands/admin/helpers.rs index 4820f96f28..462af9233e 100644 --- a/crates/sqlbuild-cli/tests/native_commands/admin/helpers.rs +++ b/crates/sqlbuild-cli/tests/native_commands/admin/helpers.rs @@ -9,26 +9,42 @@ use uuid::Uuid; use crate::test_types::TestControl; +/// The JSON result, asserting that `--json` prints nothing else. pub(crate) fn administer(control: &TestControl, arguments: &[&str]) -> Value { - let output = invoke_admin(control, arguments); + let output = invoke_admin(control, &[arguments, &["--json"]].concat()); assert!( output.status.success(), "{}", String::from_utf8_lossy(&output.stderr) ); - assert_eq!( - String::from_utf8_lossy(&output.stderr), - "Opening control store...\nControl store ready\nControl administration completed successfully\n" - ); + assert_eq!(without_opening_notice(&output), ""); serde_json::from_slice(&output.stdout).expect("JSON-only admin stdout") } +/// Stderr less the notice a slow open adds, which a loaded machine can cause. +pub(crate) fn without_opening_notice(output: &Output) -> String { + String::from_utf8_lossy(&output.stderr) + .replace("Opening control store...\nControl store ready\n", "") +} + pub(crate) fn invoke_admin(control: &TestControl, arguments: &[&str]) -> Output { admin_command(control, arguments) .output() .expect("native administration process") } +/// `invoke_admin` with one more environment variable, such as the one `--key-from-env` names. +pub(crate) fn invoke_admin_with( + control: &TestControl, + arguments: &[&str], + (name, value): (&str, &str), +) -> Output { + admin_command(control, arguments) + .env(name, value) + .output() + .expect("native administration process") +} + fn admin_command(control: &TestControl, arguments: &[&str]) -> Command { let mut command = Command::new( control @@ -46,7 +62,7 @@ fn admin_command(control: &TestControl, arguments: &[&str]) -> Command { } pub(crate) fn invoke_password(control: &TestControl, principal: &str, input: &[u8]) -> Output { - let mut child = admin_command(control, &["set-password", principal]) + let mut child = admin_command(control, &["set-password", principal, "--json"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -115,3 +131,19 @@ pub(crate) fn audit_actions(control: &TestControl, bearer: &str) -> Vec .collect::>() .expect("decode audit") } + +/// The status of reading the bootstrap with `key` from an address the server doesn't name. +pub(crate) async fn keyed_bootstrap_status(url: &str, key: &str) -> u16 { + reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .expect("HTTP client") + .get(format!("{url}/api/control/bootstrap")) + .header(reqwest::header::HOST, "10.20.30.40:8000") + .bearer_auth(key) + .send() + .await + .expect("keyed request") + .status() + .as_u16() +} diff --git a/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs b/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs index be6ed9f890..7179383d6d 100644 --- a/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs +++ b/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs @@ -218,6 +218,7 @@ fn given_a_committed_admin_operation_when_json_output_is_lost_then_all_response_ "admin", "create-location", &"x".repeat(test_case.name_bytes), + "--json", ]) .current_dir(directory.path()) .env("PATH", "") @@ -237,8 +238,8 @@ fn given_a_committed_admin_operation_when_json_output_is_lost_then_all_response_ test_case.description ); assert_eq!( - String::from_utf8_lossy(&output.stderr), - "Opening control store...\nControl store ready\nControl administration JSON result delivery failed; changes may already be committed\n", + crate::admin_helpers::without_opening_notice(&output), + "Control administration result delivery failed; changes may already be committed\n", "{}", test_case.description ); diff --git a/crates/sqlbuild-cli/tests/native_commands/admin/test_output.rs b/crates/sqlbuild-cli/tests/native_commands/admin/test_output.rs new file mode 100644 index 0000000000..d2c671fa08 --- /dev/null +++ b/crates/sqlbuild-cli/tests/native_commands/admin/test_output.rs @@ -0,0 +1,264 @@ +//! sqb admin says what it did on stderr and keeps stdout for a bare secret, plain rows or `--json`. + +use crate::admin_helpers::{administer, invoke_admin, without_opening_notice}; +use crate::helpers::{api_ready, start_control}; +use crate::test_types::AdminOutputTestCase; +#[cfg(unix)] +use crate::test_types::{AdminOpeningTestCase, SecretDeliveryTestCase}; + +#[test] +fn given_admin_commands_without_json_when_they_run_then_each_prints_one_line_and_stdout_only_a_secret_or_rows() + { + let test_cases = [ + AdminOutputTestCase { + description: "a location", + arguments: &["create-location", "inventory"], + expected_stdout: ("", 0), + expected_line: "Registered location inventory (", + }, + AdminOutputTestCase { + description: "a location label with a line break", + arguments: &["create-location", "north\nwest"], + expected_stdout: ("", 0), + expected_line: "Registered location north\\nwest (", + }, + AdminOutputTestCase { + description: "a person", + arguments: &["create-principal", "kim"], + expected_stdout: ("", 0), + expected_line: "Created person kim (", + }, + AdminOutputTestCase { + description: "a recovered admin", + arguments: &["grant-admin", "{person}"], + expected_stdout: ("", 0), + expected_line: "Made sam ({person}) an admin", + }, + AdminOutputTestCase { + description: "an issued token alone on stdout", + arguments: &[ + "issue-location-token", + "{location}", + "--expires-at", + "2099-11-20T14:30:00Z", + ], + expected_stdout: ("", 1), + expected_line: "Issued a location token for orders (", + }, + AdminOutputTestCase { + description: "a rotated token alone on stdout", + arguments: &["rotate-token", "{token}"], + expected_stdout: ("", 1), + expected_line: "Replaced token {token} with ", + }, + AdminOutputTestCase { + description: "a revoked token", + arguments: &["revoke-token", "{token}"], + expected_stdout: ("", 0), + expected_line: "Revoked token {token}", + }, + AdminOutputTestCase { + description: "a new key alone on stdout", + arguments: &["create-service-account", "ci-runner", "--role", "developer"], + expected_stdout: ("sqbk_", 1), + expected_line: "Created service account ci-runner (", + }, + AdminOutputTestCase { + description: "a rotated key alone on stdout", + arguments: &["rotate-service-account", "orders-deploy"], + expected_stdout: ("sqbk_", 1), + expected_line: "Rotated the key of service account orders-deploy (", + }, + AdminOutputTestCase { + description: "a disabled account", + arguments: &["disable-service-account", "orders-deploy"], + expected_stdout: ("", 0), + expected_line: "Disabled service account orders-deploy (", + }, + AdminOutputTestCase { + description: "an enabled account", + arguments: &["enable-service-account", "orders-deploy"], + expected_stdout: ("", 0), + expected_line: "Enabled service account orders-deploy (", + }, + AdminOutputTestCase { + description: "a list as plain rows", + arguments: &["list-service-accounts"], + expected_stdout: ("orders-deploy", 1), + expected_line: "", + }, + AdminOutputTestCase { + description: "an absent location request", + arguments: &["location-work", "{person}"], + expected_stdout: ("", 0), + expected_line: "No location request {person}", + }, + ]; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + for test_case in test_cases { + runtime.block_on(async { + let mut control = start_control(&["server", "--port", "0", "--no-scheduler"]); + api_ready(&mut control).await; + let field = |value: &serde_json::Value| value.as_str().expect("identity").to_owned(); + let location = + field(&administer(&control, &["create-location", "orders"])["location_id"]); + let expiry = "2099-01-01T00:00:00Z"; + let issued = administer( + &control, + &["issue-location-token", &location, "--expires-at", expiry], + ); + let token = field(&issued["identity"]["token_id"]); + let person = field(&administer(&control, &["create-principal", "sam"])["principal_id"]); + let account = [ + "create-service-account", + "orders-deploy", + "--role", + "viewer", + ]; + administer(&control, &account); + let fill = |text: &str| { + text.replace("{location}", &location) + .replace("{person}", &person) + .replace("{token}", &token) + }; + let arguments: Vec = + test_case.arguments.iter().map(|text| fill(text)).collect(); + let arguments: Vec<&str> = arguments.iter().map(String::as_str).collect(); + let output = invoke_admin(&control, &arguments); + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let stderr = without_opening_notice(&output); + let expected = fill(test_case.expected_line); + let secret = stdout.trim_end(); + assert_eq!( + ( + output.status.success(), + stdout.starts_with(test_case.expected_stdout.0), + stdout.lines().count(), + stderr.starts_with(&expected), + stderr.lines().count(), + secret.is_empty() || !stderr.contains(secret), + ), + ( + true, + true, + test_case.expected_stdout.1, + true, + usize::from(!expected.is_empty()), + true, + ), + "{}: {stderr}", + test_case.description + ); + #[cfg(unix)] + crate::helpers::terminate(&mut control).await; + }); + } +} + +#[cfg(unix)] +#[test] +fn given_a_verbose_or_slow_open_when_sqb_admin_runs_then_it_says_the_store_opens() { + let test_cases = [ + AdminOpeningTestCase { + description: "--verbose", + arguments: &["admin", "create-location", "orders", "--verbose"], + held_milliseconds: 0, + expected_stdout_empty: true, + expected_stderr_prefix: "Opening control store...\nControl store ready\nRegistered location orders (", + }, + AdminOpeningTestCase { + description: "a store that takes noticeably long to open", + arguments: &["admin", "create-location", "orders"], + held_milliseconds: 2500, + expected_stdout_empty: true, + expected_stderr_prefix: "Opening control store...\nControl store ready\nRegistered location orders (", + }, + AdminOpeningTestCase { + description: "--json with --verbose keeps stdout to the result", + arguments: &["admin", "create-location", "orders", "--json", "-v"], + held_milliseconds: 0, + expected_stdout_empty: false, + expected_stderr_prefix: "Opening control store...\nControl store ready\n", + }, + ]; + for test_case in test_cases { + let directory = tempfile::tempdir().expect("installation"); + let binary = crate::helpers::isolated_binary(directory.path()); + let state = directory.path().join(".sqlbuild"); + std::fs::create_dir(&state).expect("state directory"); + let writer = rusqlite::Connection::open(state.join("control.sqlite3")).expect("store"); + writer + .execute_batch("BEGIN EXCLUSIVE") + .expect("hold the store"); + let child = std::process::Command::new(binary) + .args(test_case.arguments) + .current_dir(directory.path()) + .env("PATH", "") + .env_remove("SQLBUILD_CONTROL_DATABASE_URL") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("native administration"); + std::thread::sleep(std::time::Duration::from_millis( + test_case.held_milliseconds, + )); + writer.execute_batch("ROLLBACK").expect("release the store"); + let output = child.wait_with_output().expect("administration output"); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert_eq!( + ( + output.status.success(), + output.stdout.is_empty(), + stderr.starts_with(test_case.expected_stderr_prefix), + ), + (true, test_case.expected_stdout_empty, true), + "{}: {stderr}", + test_case.description + ); + } +} + +#[cfg(unix)] +#[test] +fn given_an_issued_secret_when_stdout_fails_then_it_fails_without_printing_the_line_or_the_secret() +{ + let test_cases = [SecretDeliveryTestCase { + description: "a new service account key to a full device", + expected_exit: 1, + expected_stderr: "Control administration result delivery failed; changes may already be committed\n", + }]; + for test_case in test_cases { + let directory = tempfile::tempdir().expect("installation"); + let output = std::process::Command::new(crate::helpers::isolated_binary(directory.path())) + .args([ + "admin", + "create-service-account", + "orders-deploy", + "--role", + "viewer", + ]) + .current_dir(directory.path()) + .env("PATH", "") + .env_remove("SQLBUILD_CONTROL_DATABASE_URL") + .stdout( + std::fs::OpenOptions::new() + .write(true) + .open("/dev/full") + .expect("full device"), + ) + .output() + .expect("native administration"); + assert_eq!( + ( + output.status.code(), + without_opening_notice(&output).as_str() + ), + (Some(test_case.expected_exit), test_case.expected_stderr), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/tests/native_commands/admin/test_passwords.rs b/crates/sqlbuild-cli/tests/native_commands/admin/test_passwords.rs index ed64b7643c..b837486329 100644 --- a/crates/sqlbuild-cli/tests/native_commands/admin/test_passwords.rs +++ b/crates/sqlbuild-cli/tests/native_commands/admin/test_passwords.rs @@ -73,7 +73,7 @@ fn given_local_store_ownership_when_create_user_runs_then_only_the_first_process } let initialized: i64 = connection.query_row("SELECT COUNT(*) FROM sqb_security_audit WHERE action='admin.initialized' AND actor='local-control-store-owner'",[],|row| row.get(0)).expect("bootstrap audit"); assert_eq!(initialized,1); - let recovery = invoke_admin(&control, &["grant-admin", id.as_str()]); + let recovery = invoke_admin(&control, &["grant-admin", id.as_str(), "--json"]); assert!(recovery.status.success(), "{}", String::from_utf8_lossy(&recovery.stderr)); assert_eq!(serde_json::from_slice::(&recovery.stdout).expect("JSON-only grant"), json!({"principal_id":id,"role":"admin"})); let audits: i64 = connection.query_row("SELECT COUNT(*) FROM sqb_security_audit WHERE action='admin.granted'",[],|row| row.get(0)).expect("grant audit"); diff --git a/crates/sqlbuild-cli/tests/native_commands/admin/test_service_accounts.rs b/crates/sqlbuild-cli/tests/native_commands/admin/test_service_accounts.rs new file mode 100644 index 0000000000..6acdabe3c6 --- /dev/null +++ b/crates/sqlbuild-cli/tests/native_commands/admin/test_service_accounts.rs @@ -0,0 +1,157 @@ +//! The control-store owner manages service accounts with sqb admin; a key printed once calls the server. + +use serde_json::Value; + +use crate::admin_helpers::{administer, invoke_admin_with, keyed_bootstrap_status}; +use crate::helpers::{api_ready, start_control}; +use crate::test_types::{ + GeneratedKeyCliTestCase, ImportedKeyCliTestCase, RefusedServiceAccountCliTestCase, +}; + +const KEY_VARIABLE: &str = "SQB_TEST_IMPORTED_KEY"; + +#[test] +fn given_a_generated_key_when_the_owner_rotates_and_disables_with_sqb_admin_then_only_working_keys_call_the_server() + { + let test_cases = [GeneratedKeyCliTestCase { + description: "a key printed once works until rotated away or disabled", + arguments: &["--role", "developer", "--description", "Release pipeline"], + expected_role: "developer", + expected_statuses: [200, 200, 401, 401, 200], + }]; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + for test_case in test_cases { + runtime.block_on(async { + let mut control = start_control(&["server", "--port", "0", "--no-scheduler"]); + let url = api_ready(&mut control).await; + let mut arguments = vec!["create-service-account", "orders-deploy"]; + arguments.extend_from_slice(test_case.arguments); + let created = administer(&control, &arguments); + let key = created["key"].as_str().expect("printed key").to_owned(); + let listed = administer(&control, &["list-service-accounts"]).to_string(); + assert_eq!( + ( + created["role"].as_str(), + created["key_prefix"].as_str(), + listed.contains("orders-deploy") && !listed.contains(&key[5..]) + ), + (Some(test_case.expected_role), Some(&key[..11]), true), + "{}", + test_case.description + ); + let made = keyed_bootstrap_status(&url, &key).await; + administer( + &control, + &[ + "rotate-service-account", + "orders-deploy", + "--overlap-minutes", + "30", + ], + ); + let in_overlap = keyed_bootstrap_status(&url, &key).await; + let third = administer(&control, &["rotate-service-account", "orders-deploy"]); + let third = third["key"].as_str().expect("third key").to_owned(); + let replaced = keyed_bootstrap_status(&url, &key).await; + administer(&control, &["disable-service-account", "orders-deploy"]); + let disabled = keyed_bootstrap_status(&url, &third).await; + administer(&control, &["enable-service-account", "orders-deploy"]); + let enabled = keyed_bootstrap_status(&url, &third).await; + assert_eq!( + [made, in_overlap, replaced, disabled, enabled], + test_case.expected_statuses, + "{}", + test_case.description + ); + }); + } +} + +#[test] +fn given_a_key_in_an_environment_variable_when_the_owner_imports_it_then_it_calls_the_server_unprinted() + { + let test_cases = [ImportedKeyCliTestCase { + description: "an imported key of 32 characters after sqbk_", + key: "sqbk_0123456789abcdefghijABCDEFGHIJKL", + expected_status: 200, + expected_key_printed: false, + }]; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + for test_case in test_cases { + runtime.block_on(async { + let mut control = start_control(&["server", "--port", "0", "--no-scheduler"]); + let url = api_ready(&mut control).await; + let output = invoke_admin_with( + &control, + &[ + "create-service-account", + "orders-deploy", + "--role", + "viewer", + "--key-from-env", + KEY_VARIABLE, + ], + (KEY_VARIABLE, test_case.key), + ); + assert_eq!( + ( + output.status.success(), + !output.stdout.is_empty() + || String::from_utf8_lossy(&output.stderr).contains(test_case.key), + keyed_bootstrap_status(&url, test_case.key).await + ), + ( + true, + test_case.expected_key_printed, + test_case.expected_status + ), + "{}", + test_case.description + ); + }); + } +} + +#[test] +fn given_a_bad_import_when_the_owner_creates_a_service_account_then_it_is_refused_and_nothing_is_created() + { + let test_cases = [ + RefusedServiceAccountCliTestCase { + description: "an imported key shorter than 32 characters after sqbk_", + arguments: &["--role", "viewer", "--key-from-env", KEY_VARIABLE], + imported_key: "sqbk_too-short-for-a-key", + expected_error: "at least 32 characters", + }, + RefusedServiceAccountCliTestCase { + description: "--key-from-env naming an unset variable", + arguments: &["--role", "viewer", "--key-from-env", "SQB_TEST_UNSET_KEY"], + imported_key: "", + expected_error: "SQB_TEST_UNSET_KEY, which is not set", + }, + ]; + for test_case in test_cases { + let control = start_control(&["server", "--port", "0", "--no-scheduler"]); + let mut arguments = vec!["create-service-account", "orders-deploy"]; + arguments.extend_from_slice(test_case.arguments); + let output = + invoke_admin_with(&control, &arguments, (KEY_VARIABLE, test_case.imported_key)); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert_eq!( + ( + output.status.success(), + output.stdout.is_empty(), + stderr.contains(test_case.expected_error), + administer(&control, &["list-service-accounts"]) + ), + (false, true, true, Value::Array(Vec::new())), + "{}: {stderr}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/tests/native_commands/republish/helpers.rs b/crates/sqlbuild-cli/tests/native_commands/republish/helpers.rs new file mode 100644 index 0000000000..4edf468681 --- /dev/null +++ b/crates/sqlbuild-cli/tests/native_commands/republish/helpers.rs @@ -0,0 +1,85 @@ +//! A fake plain-HTTP proxy that records what `sqb location republish` sends to a network origin. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::process::{Command, Output}; +use std::sync::mpsc; + +use serde_json::json; + +pub(crate) const LOCATION_ID: &str = "00000000-0000-0000-0000-000000000001"; +pub(crate) const NETWORK_ORIGIN: &str = "http://control.example.com:8000"; + +/// Run the command through a proxy answering with `states` in order; its output and each request's head. +pub(crate) fn republish_through_proxy( + key: Option<&str>, + states: &[&str], + arguments: &[&str], +) -> (Output, Vec) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind fake proxy"); + let proxy = format!("http://{}", listener.local_addr().expect("proxy address")); + let bodies: Vec = states.iter().map(|state| status(state)).collect(); + let (sent, received) = mpsc::channel(); + std::thread::spawn(move || answer(&listener, &bodies, &sent)); + let home = tempfile::tempdir().expect("isolated home"); + let mut command = Command::new(env!("CARGO_BIN_EXE_sqb")); + command + .args(["location", "republish", "--server", NETWORK_ORIGIN]) + .args(["--location-id", LOCATION_ID, "--target", "production"]) + .args(arguments) + .current_dir(home.path()) + .env("HOME", home.path()) + .env("XDG_CONFIG_HOME", home.path()) + .env("XDG_DATA_HOME", home.path()) + .env("XDG_STATE_HOME", home.path()) + .env("HTTP_PROXY", &proxy) + .env("http_proxy", &proxy) + .env_remove("NO_PROXY") + .env_remove("no_proxy") + .env_remove("SQLBUILD_API_KEY"); + command.envs(key.map(|value| ("SQLBUILD_API_KEY", value))); + let output = command.output().expect("run republish"); + (output, received.try_iter().collect()) +} + +fn answer(listener: &std::net::TcpListener, bodies: &[String], sent: &mpsc::Sender) { + for body in bodies { + let (stream, _) = listener.accept().expect("accept request"); + let mut reader = BufReader::new(stream); + let lines: Vec = reader + .by_ref() + .lines() + .map(|line| line.expect("request head")) + .take_while(|line| !line.trim().is_empty()) + .collect(); + let head: String = lines.join("\n"); + let length: usize = head + .to_ascii_lowercase() + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .map_or(0, |value| value.trim().parse().expect("content length")); + reader + .read_exact(&mut vec![0; length]) + .expect("request body"); + sent.send(head).expect("record request"); + write!( + reader.get_mut(), + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ) + .expect("response"); + } +} + +fn status(state: &str) -> String { + json!({ + "request_id": "00000000-0000-0000-0000-000000000002", + "location_id": LOCATION_ID, + "target": "production", + "state": state, + "requested_by": "orders-deploy", + "reason": "deploy", + "requested_at": "2026-11-22T09:00:00Z", + "expires_at": "2026-11-22T09:15:00Z", + }) + .to_string() +} diff --git a/crates/sqlbuild-cli/tests/native_commands/test_control.rs b/crates/sqlbuild-cli/tests/native_commands/test_control.rs index b1673e9d9d..00d39f57e7 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_control.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_control.rs @@ -379,13 +379,13 @@ fn given_a_control_store_when_running_server_migrate_then_dry_run_lists_and_migr StoreMigrationCommandTestCase { description: "migrate an empty store", arguments: &["server", "migrate"], - expected_stdout: "The control store is empty: created schema version 5.\n", + expected_stdout: "The control store is empty: created schema version 9.\n", expected_store: true, }, StoreMigrationCommandTestCase { description: "dry run on a current store", arguments: &["server", "migrate", "--dry-run"], - expected_stdout: "The control store is at schema version 5: nothing to migrate.\n", + expected_stdout: "The control store is at schema version 9: nothing to migrate.\n", expected_store: true, }, ]; diff --git a/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs b/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs index 3ad4b99559..780dad3cec 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs @@ -80,6 +80,16 @@ fn given_location_health_reports_when_checking_health_then_down_falling_back_or_ expected_state: "healthy", expected_exit: 0, }, + LocationHealthTestCase { + description: "a discover function failed and its set serves the last good items", + reports: &[ + r#"{"kind":"connection","generation":2,"healthy":true}"#, + r#"{"kind":"discovery","generation":2,"sets":[{"name":"orders_plan","status":"failed","items":2}]}"#, + ], + other_target_connections: 0, + expected_state: "discovery_failed", + expected_exit: 0, + }, LocationHealthTestCase { description: "the warehouse connection check failed", reports: &[r#"{"kind":"connection","generation":2,"healthy":false}"#], diff --git a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs index bd99c87d57..b04eb99abd 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_proxy.rs @@ -3,7 +3,11 @@ use reqwest::{Client, StatusCode, header}; use serde_json::{Value, json}; +#[cfg(unix)] +use crate::admin_helpers::administer; use crate::helpers::{api_ready, start_control_in, wait_for_exit}; +#[cfg(unix)] +use crate::test_types::NetworkKeyTestCase; use crate::test_types::{ ProxyCliTestCase, ProxyRemotePeerTestCase, ProxyStartupTestCase, ServerConfigurationTestCase, }; @@ -28,7 +32,7 @@ fn given_an_owner_configured_proxy_when_requests_carry_a_subject_then_only_expli runtime.block_on(async { let directory = tempfile::tempdir().expect("prepared proxy installation"); let provisioned = std::process::Command::new(env!("CARGO_BIN_EXE_sqb")) - .args(["admin", "create-principal", "orders-reader"]) + .args(["admin", "create-principal", "orders-reader", "--json"]) .current_dir(directory.path()).env("PATH", "") .env_remove("SQLBUILD_CONTROL_DATABASE_URL").output().expect("native owner provisioning"); assert!(provisioned.status.success()); @@ -443,3 +447,106 @@ fn given_the_default_trusted_peers_when_a_non_loopback_peer_sends_the_username_h }); } } + +#[cfg(unix)] +#[test] +fn given_a_plain_http_proxy_server_open_to_the_network_when_an_untrusted_peer_calls_then_only_its_key_gets_in() + { + let test_cases = [NetworkKeyTestCase { + description: "an http:// origin, a foreign Host and a peer outside trusted_peers", + configuration: "[server]\nhost = \"0.0.0.0\"\n\n[trusted_proxy]\norigin = \"http://control.example.com\"\ntrusted_peers = [\"192.0.2.10\"]\n", + host: "scripts.example.net:8000", + expected_statuses: [ + StatusCode::OK, + StatusCode::OK, + StatusCode::UNAUTHORIZED, + StatusCode::UNAUTHORIZED, + ], + expected_name: "orders-deploy", + }]; + let route = std::net::UdpSocket::bind("0.0.0.0:0").expect("UDP socket"); + route.connect("192.0.2.1:9").expect("a non-loopback route"); + let peer = route.local_addr().expect("route address").ip(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + for test_case in test_cases { + runtime.block_on(async { + let directory = tempfile::tempdir().expect("proxy installation"); + std::fs::write( + directory.path().join("server.toml"), + test_case.configuration, + ) + .expect("server configuration"); + let mut control = start_control_in( + directory, + &[ + "server", + "--port", + "0", + "--no-scheduler", + "--config", + "server.toml", + ], + ); + let ready = api_ready(&mut control).await; + let (_, port) = ready.rsplit_once(':').expect("listening port"); + let url = format!("http://{peer}:{port}"); + let created = administer( + &control, + &["create-service-account", "orders-deploy", "--role", "admin"], + ); + let key = created["key"].as_str().expect("printed key"); + let client = Client::builder() + .no_proxy() + .timeout(std::time::Duration::from_secs(5)) + .build() + .expect("HTTP client"); + let bootstrap = format!("{url}/api/control/bootstrap"); + let read = client + .get(&bootstrap) + .header(header::HOST, test_case.host) + .bearer_auth(key) + .send() + .await + .expect("keyed read"); + let read_status = read.status(); + let body: Value = read.json().await.unwrap_or(Value::Null); + let write = client + .post(format!("{url}/api/admin/service-accounts")) + .header(header::HOST, test_case.host) + .bearer_auth(key) + .json(&json!({"name": "report-export", "role": "viewer"})) + .send() + .await + .expect("keyed write"); + let named = |host: &'static str| { + client + .get(&bootstrap) + .header(header::HOST, host) + .header("x-sqb-user", "orders-reader") + .send() + }; + let statuses = [ + read_status, + write.status(), + named(test_case.host) + .await + .expect("username under the foreign Host") + .status(), + named("control.example.com") + .await + .expect("username under the origin's Host") + .status(), + ]; + assert_eq!( + (statuses, body["access"]["name"].as_str()), + (test_case.expected_statuses, Some(test_case.expected_name)), + "{}: peer {peer}", + test_case.description + ); + crate::helpers::terminate(&mut control).await; + }); + } +} diff --git a/crates/sqlbuild-cli/tests/native_commands/test_republish.rs b/crates/sqlbuild-cli/tests/native_commands/test_republish.rs new file mode 100644 index 0000000000..b0c2abff59 --- /dev/null +++ b/crates/sqlbuild-cli/tests/native_commands/test_republish.rs @@ -0,0 +1,114 @@ +//! An API key republishes over plain HTTP with one warning; a saved session still needs HTTPS. + +use crate::republish_helpers::{NETWORK_ORIGIN, republish_through_proxy}; +use crate::test_types::RepublishCliTestCase; + +const KEY: &str = "sqbk_synthetic_orders_deploy_key_0000000000"; +const WARNING: &str = "travels unencrypted over HTTP"; + +#[test] +fn given_a_plain_http_network_server_when_republishing_then_a_key_warns_and_a_session_requires_https() + { + let test_cases = [ + RepublishCliTestCase { + description: "a key is sent over plain HTTP", + key: Some(KEY), + states: &["pending"], + arguments: &[], + expected_exit: 0, + expected_methods: &["POST"], + expected_warnings: 1, + expected_stderr: "Republish accepted", + }, + RepublishCliTestCase { + description: "waiting polls with the same key and warns once", + key: Some(KEY), + states: &["pending", "pending", "published"], + arguments: &["--wait"], + expected_exit: 0, + expected_methods: &["POST", "GET", "GET"], + expected_warnings: 1, + expected_stderr: "Republish published a snapshot", + }, + RepublishCliTestCase { + description: "a failed publish exits one", + key: Some(KEY), + states: &["pending", "failed"], + arguments: &["--wait"], + expected_exit: 1, + expected_methods: &["POST", "GET"], + expected_warnings: 1, + expected_stderr: "Republish failed", + }, + RepublishCliTestCase { + description: "waiting no seconds reports a pending republish", + key: Some(KEY), + states: &["pending"], + arguments: &["--wait", "--timeout", "0"], + expected_exit: 2, + expected_methods: &["POST"], + expected_warnings: 1, + expected_stderr: "Republish is still pending", + }, + RepublishCliTestCase { + description: "a session refuses plain HTTP before sending anything", + key: None, + states: &["pending"], + arguments: &[], + expected_exit: 2, + expected_methods: &[], + expected_warnings: 0, + expected_stderr: "Republish request failed", + }, + RepublishCliTestCase { + description: "a blank key is not a session", + key: Some(" "), + states: &["pending"], + arguments: &[], + expected_exit: 2, + expected_methods: &[], + expected_warnings: 0, + expected_stderr: "SQLBUILD_API_KEY must not be blank", + }, + ]; + + for test_case in test_cases { + let (output, requests) = + republish_through_proxy(test_case.key, test_case.states, test_case.arguments); + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + let methods: Vec<&str> = requests + .iter() + .filter_map(|head| head.split_whitespace().next()) + .collect(); + let bearers: usize = requests + .iter() + .filter(|head| { + head.to_ascii_lowercase() + .contains(&format!("authorization: bearer {KEY}").to_ascii_lowercase()) + }) + .filter(|head| head.contains(&format!(" {NETWORK_ORIGIN}/api/control/locations/"))) + .count(); + + assert_eq!( + ( + output.status.code(), + methods, + bearers, + stderr.matches(WARNING).count(), + stderr.contains(test_case.expected_stderr), + stderr.contains(KEY) || stdout.contains(KEY), + ), + ( + Some(test_case.expected_exit), + test_case.expected_methods.to_vec(), + test_case.expected_methods.len(), + test_case.expected_warnings, + true, + false, + ), + "{}: {stderr}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/tests/native_commands/test_types.rs b/crates/sqlbuild-cli/tests/native_commands/test_types.rs index b0bac34d91..d5e6ea1b6f 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_types.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_types.rs @@ -72,6 +72,19 @@ pub(crate) struct ProxyRemotePeerTestCase { pub(crate) expected_warnings: usize, } +/// A trusted-proxy server over plain HTTP, open to the network and reached by a peer that isn't the proxy. +#[cfg(unix)] +pub(crate) struct NetworkKeyTestCase { + pub(crate) description: &'static str, + pub(crate) configuration: &'static str, + /// The Host the peer sends, neither the origin's nor an allowed one. + pub(crate) host: &'static str, + /// A keyed read and write, then the username header without a key under that Host and the origin's. + pub(crate) expected_statuses: [reqwest::StatusCode; 4], + /// Whom the keyed read authenticated as. + pub(crate) expected_name: &'static str, +} + pub(crate) struct ServerConfigurationTestCase { pub(crate) description: &'static str, pub(crate) configuration: &'static str, @@ -109,3 +122,70 @@ pub(crate) struct StoreMigrationCommandTestCase { /// Whether the SQLite store file exists after the command. pub(crate) expected_store: bool, } + +pub(crate) struct GeneratedKeyCliTestCase { + pub(crate) description: &'static str, + /// The arguments of `sqb admin create-service-account` after the name. + pub(crate) arguments: &'static [&'static str], + pub(crate) expected_role: &'static str, + /// What the key's bootstrap read answers: when made, in the overlap, once replaced, disabled, enabled. + pub(crate) expected_statuses: [u16; 5], +} + +pub(crate) struct ImportedKeyCliTestCase { + pub(crate) description: &'static str, + pub(crate) key: &'static str, + pub(crate) expected_status: u16, + /// Whether the JSON result repeats the key. + pub(crate) expected_key_printed: bool, +} + +pub(crate) struct RefusedServiceAccountCliTestCase { + pub(crate) description: &'static str, + pub(crate) arguments: &'static [&'static str], + /// The value of `SQB_TEST_IMPORTED_KEY`. + pub(crate) imported_key: &'static str, + pub(crate) expected_error: &'static str, +} + +/// An admin command without `--json`, run after one location, person, token and service account exist. +pub(crate) struct AdminOutputTestCase { + pub(crate) description: &'static str, + /// Arguments, with `{location}`, `{person}` and `{token}` filled in. + pub(crate) arguments: &'static [&'static str], + /// How stdout starts, and how many lines it has. + pub(crate) expected_stdout: (&'static str, usize), + /// How the one stderr line starts; empty for none. + pub(crate) expected_line: &'static str, +} + +/// A store that opens verbosely or slowly. +#[cfg(unix)] +pub(crate) struct AdminOpeningTestCase { + pub(crate) description: &'static str, + pub(crate) arguments: &'static [&'static str], + /// How long another writer holds the new store. + pub(crate) held_milliseconds: u64, + pub(crate) expected_stdout_empty: bool, + pub(crate) expected_stderr_prefix: &'static str, +} + +/// A committed secret that stdout couldn't take. +#[cfg(unix)] +pub(crate) struct SecretDeliveryTestCase { + pub(crate) description: &'static str, + pub(crate) expected_exit: i32, + pub(crate) expected_stderr: &'static str, +} + +/// One invocation against an `http://` network origin, and what the client did with the credential. +pub(crate) struct RepublishCliTestCase { + pub(crate) description: &'static str, + pub(crate) key: Option<&'static str>, + pub(crate) states: &'static [&'static str], + pub(crate) arguments: &'static [&'static str], + pub(crate) expected_exit: i32, + pub(crate) expected_methods: &'static [&'static str], + pub(crate) expected_warnings: usize, + pub(crate) expected_stderr: &'static str, +} diff --git a/crates/sqlbuild-core/src/build_progress/_helpers/text.rs b/crates/sqlbuild-core/src/build_progress/_helpers/text.rs index fb6101e8d0..67933791b1 100644 --- a/crates/sqlbuild-core/src/build_progress/_helpers/text.rs +++ b/crates/sqlbuild-core/src/build_progress/_helpers/text.rs @@ -135,3 +135,13 @@ pub(crate) fn abbreviated_rows(count: i64) -> String { } format!("{} {label}", format_thousands(i128::from(count))) } + +/// `45s`, `2m10s` or `1h02m05s`. +pub(crate) fn whole_elapsed(seconds: u64) -> String { + let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60); + match (hours, minutes) { + (0, 0) => format!("{seconds}s"), + (0, _) => format!("{minutes}m{seconds:02}s"), + _ => format!("{hours}h{minutes:02}m{seconds:02}s"), + } +} diff --git a/crates/sqlbuild-core/src/build_progress/constants.rs b/crates/sqlbuild-core/src/build_progress/constants.rs index 73f5985fd3..c0a30dbb22 100644 --- a/crates/sqlbuild-core/src/build_progress/constants.rs +++ b/crates/sqlbuild-core/src/build_progress/constants.rs @@ -37,3 +37,9 @@ pub(crate) const INSUFFICIENT: &str = "insufficient"; pub(crate) const DELTA_AND_FINAL: &str = "delta_and_final"; pub(crate) const TIMEOUT_OUTCOME: &str = "timeout"; pub(crate) const TIMEOUT_CODE: &str = "C417"; + +/// Seconds before each heartbeat of captured build output; the last repeats. +pub(crate) const HEARTBEAT_INTERVALS: [u64; 4] = [30, 60, 120, 300]; + +/// How many running nodes a heartbeat names before `+N more`. +pub(crate) const HEARTBEAT_NAMES: usize = 3; diff --git a/crates/sqlbuild-core/src/build_progress/main/heartbeat_interval.rs b/crates/sqlbuild-core/src/build_progress/main/heartbeat_interval.rs new file mode 100644 index 0000000000..787c8319fe --- /dev/null +++ b/crates/sqlbuild-core/src/build_progress/main/heartbeat_interval.rs @@ -0,0 +1,12 @@ +//! How long captured build output waits before its next heartbeat line. + +use std::time::Duration; + +use crate::build_progress::constants::HEARTBEAT_INTERVALS; + +/// The wait before heartbeat `beats + 1`: a node must first run 30 s, then 1 min, 2 min, and every 5 min after. +#[must_use] +pub fn heartbeat_interval(beats: usize) -> Duration { + let last: usize = HEARTBEAT_INTERVALS.len() - 1; + Duration::from_secs(HEARTBEAT_INTERVALS[beats.min(last)]) +} diff --git a/crates/sqlbuild-core/src/build_progress/main/heartbeat_message.rs b/crates/sqlbuild-core/src/build_progress/main/heartbeat_message.rs new file mode 100644 index 0000000000..01e5608472 --- /dev/null +++ b/crates/sqlbuild-core/src/build_progress/main/heartbeat_message.rs @@ -0,0 +1,44 @@ +//! The one combined line captured build output prints while nodes run for a long time. + +use crate::build_progress::_helpers::text::whole_elapsed; +use crate::build_progress::constants::HEARTBEAT_NAMES; +use crate::build_progress::models::RunningNodeText; +use crate::cli_text::models::CliStyle; +use crate::number_text::main::format_thousands::format_thousands; + +/// `… still running (N)` and the longest-running nodes with their elapsed time and, where known, rows so far. +#[must_use] +pub fn heartbeat_message(running: &[RunningNodeText], style: CliStyle) -> String { + let mut longest: Vec<&RunningNodeText> = running.iter().collect(); + longest.sort_by(|left, right| { + right + .elapsed_seconds + .cmp(&left.elapsed_seconds) + .then_with(|| left.name.cmp(&right.name)) + }); + let mut parts: Vec = Vec::new(); + for node in longest.iter().take(HEARTBEAT_NAMES) { + parts.push(node_text(node, style)); + } + if longest.len() > HEARTBEAT_NAMES { + parts.push(style.muted(&format!("+{} more", longest.len() - HEARTBEAT_NAMES))); + } + format!( + "{} {}", + style.muted(&format!("… still running ({})", running.len())), + parts.join(" · ") + ) +} + +fn node_text(node: &RunningNodeText, style: CliStyle) -> String { + let rows: String = match node.rows_so_far { + Some(1) => " (1 row)".to_owned(), + Some(rows) => format!(" ({} rows)", format_thousands(i128::from(rows))), + None => String::new(), + }; + format!( + "{} {}{rows}", + style.object_name(&node.name), + whole_elapsed(node.elapsed_seconds) + ) +} diff --git a/crates/sqlbuild-core/src/build_progress/main/mod.rs b/crates/sqlbuild-core/src/build_progress/main/mod.rs index c104e9b92c..392a63cb5a 100644 --- a/crates/sqlbuild-core/src/build_progress/main/mod.rs +++ b/crates/sqlbuild-core/src/build_progress/main/mod.rs @@ -1,5 +1,7 @@ pub mod batch_progress_message; pub mod format_build_footer; +pub mod heartbeat_interval; +pub mod heartbeat_message; pub mod progress_name_width; pub mod query_diagnostic_message; pub mod render_build_spinner_line; diff --git a/crates/sqlbuild-core/src/build_progress/models.rs b/crates/sqlbuild-core/src/build_progress/models.rs index 4019321768..121ce34dbe 100644 --- a/crates/sqlbuild-core/src/build_progress/models.rs +++ b/crates/sqlbuild-core/src/build_progress/models.rs @@ -188,6 +188,14 @@ pub struct StatementText { pub phase: String, } +/// A node still running when a heartbeat line is written, with the rows it has written where known. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RunningNodeText { + pub name: String, + pub elapsed_seconds: u64, + pub rows_so_far: Option, +} + /// One completed microbatch of a model. #[derive(Clone, Debug, Default, PartialEq)] pub struct BatchProgressText { diff --git a/crates/sqlbuild-core/src/build_progress/tests/test_build_progress.rs b/crates/sqlbuild-core/src/build_progress/tests/test_build_progress.rs index e980984f8d..6de232e4c7 100644 --- a/crates/sqlbuild-core/src/build_progress/tests/test_build_progress.rs +++ b/crates/sqlbuild-core/src/build_progress/tests/test_build_progress.rs @@ -1,5 +1,7 @@ use crate::build_progress::main::batch_progress_message::batch_progress_message; use crate::build_progress::main::format_build_footer::format_build_footer; +use crate::build_progress::main::heartbeat_interval::heartbeat_interval; +use crate::build_progress::main::heartbeat_message::heartbeat_message; use crate::build_progress::main::progress_name_width::progress_name_width; use crate::build_progress::main::render_build_spinner_line::render_build_spinner_line; use crate::build_progress::main::render_failed_test_result::render_failed_test_result; @@ -7,12 +9,14 @@ use crate::build_progress::main::render_model_result::render_model_result; use crate::build_progress::main::scheduler_diagnostic_message::scheduler_diagnostic_message; use crate::build_progress::models::{ BatchProgressText, BuildResultText, ErrorText, LifecycleEventText, ModelResultText, - ModelRowFacts, NameWidthInputs, ProgressLayout, PythonNodeText, SchedulerStateText, SpinnerRow, + ModelRowFacts, NameWidthInputs, ProgressLayout, PythonNodeText, RunningNodeText, + SchedulerStateText, SpinnerRow, }; use crate::build_progress::tests::helpers::{audit, failed_model, layout, model, test}; use crate::build_progress::tests::test_types::{ - BatchProgressTestCase, FailedTestTestCase, FooterTestCase, InlineErrorTestCase, - ModelRowTestCase, NameWidthTestCase, SchedulerTestCase, SpinnerTestCase, + BatchProgressTestCase, FailedTestTestCase, FooterTestCase, HeartbeatIntervalTestCase, + HeartbeatTestCase, InlineErrorTestCase, ModelRowTestCase, NameWidthTestCase, SchedulerTestCase, + SpinnerTestCase, }; use crate::cli_text::main::format_inline_error_lines::format_inline_error_lines; use crate::cli_text::models::CliStyle; @@ -327,3 +331,77 @@ fn given_completed_batch_when_describing_then_names_model_window_rows_and_time() ); } } + +#[test] +fn given_long_running_nodes_when_a_heartbeat_is_due_then_one_line_names_the_longest_with_known_rows() + { + let node = |name: &str, elapsed_seconds: u64, rows_so_far: Option| RunningNodeText { + name: name.to_owned(), + elapsed_seconds, + rows_so_far, + }; + let test_cases = [ + HeartbeatTestCase { + description: "longest first, rows only where known", + running: vec![ + node("raw_events", 65, Some(48_210)), + node("stg_inventory", 130, None), + node("stg_shipments", 110, None), + ], + expected_text: "… still running (3) stg_inventory 2m10s · stg_shipments 1m50s · raw_events 1m05s (48,210 rows)", + }, + HeartbeatTestCase { + description: "more than three names collapse into a count", + running: vec![ + node("a", 40, None), + node("b", 3_725, Some(1)), + node("c", 31, None), + node("d", 600, None), + node("e", 5, None), + ], + expected_text: "… still running (5) b 1h02m05s (1 row) · d 10m00s · a 40s · +2 more", + }, + ]; + for test_case in test_cases { + assert_eq!( + heartbeat_message(&test_case.running, PLAIN), + test_case.expected_text, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_long_running_build_when_heartbeats_repeat_then_they_back_off_to_every_five_minutes() { + let test_cases = [ + HeartbeatIntervalTestCase { + description: "the first line waits for a node to pass 30 seconds", + beats: 0, + expected_seconds: 30, + }, + HeartbeatIntervalTestCase { + description: "the second comes a minute later", + beats: 1, + expected_seconds: 60, + }, + HeartbeatIntervalTestCase { + description: "the third two minutes later", + beats: 2, + expected_seconds: 120, + }, + HeartbeatIntervalTestCase { + description: "then every five minutes", + beats: 7, + expected_seconds: 300, + }, + ]; + for test_case in test_cases { + assert_eq!( + heartbeat_interval(test_case.beats).as_secs(), + test_case.expected_seconds, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-core/src/build_progress/tests/test_types.rs b/crates/sqlbuild-core/src/build_progress/tests/test_types.rs index 91b62d8060..5804dacbe1 100644 --- a/crates/sqlbuild-core/src/build_progress/tests/test_types.rs +++ b/crates/sqlbuild-core/src/build_progress/tests/test_types.rs @@ -1,6 +1,6 @@ use crate::build_progress::models::{ BatchProgressText, BuildResultText, ModelResultText, NameWidthInputs, PythonNodeText, - SchedulerStateText, SpinnerRow, TestResultText, + RunningNodeText, SchedulerStateText, SpinnerRow, TestResultText, }; pub(super) struct FooterTestCase { @@ -56,3 +56,15 @@ pub(super) struct BatchProgressTestCase { pub(super) batch: BatchProgressText, pub(super) expected_text: &'static str, } + +pub(super) struct HeartbeatTestCase { + pub(super) description: &'static str, + pub(super) running: Vec, + pub(super) expected_text: &'static str, +} + +pub(super) struct HeartbeatIntervalTestCase { + pub(super) description: &'static str, + pub(super) beats: usize, + pub(super) expected_seconds: u64, +} diff --git a/crates/sqlbuild-core/src/process_environment/main/env_file_shown.rs b/crates/sqlbuild-core/src/process_environment/main/env_file_shown.rs new file mode 100644 index 0000000000..6cd6516daa --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/env_file_shown.rs @@ -0,0 +1,17 @@ +//! The env file this process tree loaded, as messages name it. + +use std::path::Path; + +use crate::process_environment::main::env_file_marker::env_file_marker; +use crate::process_environment::main::project_relative_path::project_relative_path; + +/// The env file's path from the project it was chosen for, such as `.env`; `None` when none is loaded. +#[must_use] +pub fn env_file_shown() -> Option { + let marker = env_file_marker()?; + let path: String = marker.path?; + Some(project_relative_path( + Path::new(&marker.project_dir), + Path::new(&path), + )) +} diff --git a/crates/sqlbuild-core/src/process_environment/main/location_secret_fix.rs b/crates/sqlbuild-core/src/process_environment/main/location_secret_fix.rs new file mode 100644 index 0000000000..5a5a3afc00 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/location_secret_fix.rs @@ -0,0 +1,14 @@ +//! How to set a missing secret for a location, whose environment only a restart changes. + +/// Where to set `subject` and what then picks it up: `r` re-reads an env file under `sqb dev`, and only a restart reads a changed environment. +#[must_use] +pub fn location_secret_fix(subject: &str, env_file: Option<&str>) -> String { + let environment: &str = + "in the environment the location (or sqb dev) was started with, then restart it"; + match env_file { + Some(file) => format!( + "set {subject} in {file}, then restart the location (in sqb dev, press r), or {environment}" + ), + None => format!("set {subject} {environment}"), + } +} diff --git a/crates/sqlbuild-core/src/process_environment/main/mod.rs b/crates/sqlbuild-core/src/process_environment/main/mod.rs index 5b957fd669..1af4596f7a 100644 --- a/crates/sqlbuild-core/src/process_environment/main/mod.rs +++ b/crates/sqlbuild-core/src/process_environment/main/mod.rs @@ -1,9 +1,12 @@ pub mod apply_environment_overlay; pub mod env_file_marker; +pub mod env_file_shown; pub mod environment_overlay; pub mod environment_var_os; pub mod environment_vars_os; pub mod environment_without_env_file; pub mod install_environment_overlay; +pub mod location_secret_fix; pub mod marker_json; pub mod project_relative_path; +pub mod shell_secret_fix; diff --git a/crates/sqlbuild-core/src/process_environment/main/shell_secret_fix.rs b/crates/sqlbuild-core/src/process_environment/main/shell_secret_fix.rs new file mode 100644 index 0000000000..8d01fce80f --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/shell_secret_fix.rs @@ -0,0 +1,10 @@ +//! How to set a missing secret for a command run from a shell. + +/// `set in this shell or in .env`, naming the env file the project loads. +#[must_use] +pub fn shell_secret_fix(subject: &str, env_file: Option<&str>) -> String { + match env_file { + Some(file) => format!("set {subject} in this shell or in {file}"), + None => format!("set {subject} in this shell"), + } +} diff --git a/crates/sqlbuild-core/src/redaction/_helpers/mod.rs b/crates/sqlbuild-core/src/redaction/_helpers/mod.rs index d0c4d5d890..e6b4d0fd24 100644 --- a/crates/sqlbuild-core/src/redaction/_helpers/mod.rs +++ b/crates/sqlbuild-core/src/redaction/_helpers/mod.rs @@ -1 +1,2 @@ pub(crate) mod patterns; +pub(crate) mod readings; diff --git a/crates/sqlbuild-core/src/redaction/_helpers/patterns.rs b/crates/sqlbuild-core/src/redaction/_helpers/patterns.rs index ace7ba4d66..7b23b7a843 100644 --- a/crates/sqlbuild-core/src/redaction/_helpers/patterns.rs +++ b/crates/sqlbuild-core/src/redaction/_helpers/patterns.rs @@ -5,8 +5,9 @@ use std::sync::LazyLock; use regex::{Captures, Regex, RegexBuilder}; use crate::redaction::constants::{ - AUTHORIZATION_PATTERN, BARE_USERINFO_PATTERN, BEARER_PATTERN, DDL_PASSWORD_PATTERN, - PATTERN_SIZE_LIMIT, SECRET_VALUE_PATTERN, URI_CREDENTIAL_PATTERN, + AUTHORIZATION_PATTERN, BARE_USERINFO_PATTERN, BEARER_PATTERN, BEARER_REPLACEMENT, + DDL_PASSWORD_PATTERN, DDL_REPLACEMENT, PAIR_REPLACEMENT, PATTERN_SIZE_LIMIT, + SECRET_VALUE_PATTERN, URI_CREDENTIAL_PATTERN, URI_REPLACEMENT, }; pub(crate) static AUTHORIZATION: LazyLock> = @@ -40,6 +41,20 @@ pub(crate) fn substituted( } } +/// One reading's named secrets and URI passwords redacted. +pub(crate) fn named_redacted(text: &str) -> String { + let authorization: String = substituted(&AUTHORIZATION, text, PAIR_REPLACEMENT); + let bearer: String = substituted(&BEARER, &authorization, BEARER_REPLACEMENT); + let named: String = substituted(&SECRET_VALUE, &bearer, PAIR_REPLACEMENT); + let statement: String = substituted(&DDL_PASSWORD, &named, DDL_REPLACEMENT); + substituted(&URI_CREDENTIAL, &statement, URI_REPLACEMENT) +} + +/// One reading of error text, which may also hold a URI cut before its host. +pub(crate) fn error_redacted(text: &str) -> String { + bare_userinfo_redacted(&named_redacted(text)) +} + /// A port is all digits and the authority ends after it (`/`, `?`, `#`); anything else may be a password. pub(crate) fn bare_userinfo_redacted(text: &str) -> String { match BARE_USERINFO.as_ref() { diff --git a/crates/sqlbuild-core/src/redaction/_helpers/readings.rs b/crates/sqlbuild-core/src/redaction/_helpers/readings.rs new file mode 100644 index 0000000000..dcb4f6573e --- /dev/null +++ b/crates/sqlbuild-core/src/redaction/_helpers/readings.rs @@ -0,0 +1,15 @@ +//! Text with NUL reads two ways: as it is, and without NUL as it is stored. + +use crate::redaction::constants::WITHHELD_TEXT; + +/// `redact`'s text; with NUL, the whole text is withheld when either reading would change, and otherwise loses its NUL. +pub(crate) fn redacted_readings(text: &str, redact: impl Fn(&str) -> String) -> String { + if !text.contains('\0') { + return redact(text); + } + let without_nul: String = text.replace('\0', ""); + if redact(text) != text || redact(&without_nul) != without_nul { + return WITHHELD_TEXT.to_owned(); + } + without_nul +} diff --git a/crates/sqlbuild-core/src/redaction/constants.rs b/crates/sqlbuild-core/src/redaction/constants.rs index 6ff44b2168..ee2460e8de 100644 --- a/crates/sqlbuild-core/src/redaction/constants.rs +++ b/crates/sqlbuild-core/src/redaction/constants.rs @@ -36,6 +36,8 @@ pub(crate) const DDL_PASSWORD_PATTERN: &str = concat!( r#"\b(identified\s+(?:with\s+\w+\s+)?by)(\s+)("[^"\r\n]{0,512}"|'[^'\r\n]{0,512}'|[^\s,;]{1,512})"#, ); pub(crate) const DDL_REPLACEMENT: &str = "${1}${2}${4}${5}[REDACTED]"; +/// Stands in for a whole text that can't be stored as it reads. +pub(crate) const WITHHELD_TEXT: &str = "[REDACTED]"; pub(crate) const PAIR_REPLACEMENT: &str = "${1}${2}[REDACTED]"; pub(crate) const BEARER_REPLACEMENT: &str = "Bearer [REDACTED]"; pub(crate) const URI_REPLACEMENT: &str = "${1}[REDACTED]${3}${4}"; diff --git a/crates/sqlbuild-core/src/redaction/main/mod.rs b/crates/sqlbuild-core/src/redaction/main/mod.rs index a02ca5d2de..60a42d2e14 100644 --- a/crates/sqlbuild-core/src/redaction/main/mod.rs +++ b/crates/sqlbuild-core/src/redaction/main/mod.rs @@ -1,3 +1,4 @@ pub mod redact_error_text; +pub mod redact_masked_text; pub mod redact_text; pub mod secret_field_name; diff --git a/crates/sqlbuild-core/src/redaction/main/redact_error_text.rs b/crates/sqlbuild-core/src/redaction/main/redact_error_text.rs index 5aa7856753..43bf76bd12 100644 --- a/crates/sqlbuild-core/src/redaction/main/redact_error_text.rs +++ b/crates/sqlbuild-core/src/redaction/main/redact_error_text.rs @@ -1,13 +1,13 @@ //! `redact_error_text`: error text redacted before it is cut, so a cut can never expose part of a secret. -use crate::redaction::_helpers::patterns::bare_userinfo_redacted; +use crate::redaction::_helpers::patterns::error_redacted; +use crate::redaction::_helpers::readings::redacted_readings; use crate::redaction::constants::ERROR_TEXT_CHARS; -use crate::redaction::main::redact_text::redact_text; /// Named secrets and URI passwords redacted, even where a warehouse cut the URI before its host, then at most 2,000 characters; a second pass changes nothing. #[must_use] pub fn redact_error_text(text: &str) -> String { - let redacted = bare_userinfo_redacted(&redact_text(text)); + let redacted = redacted_readings(text, error_redacted); if redacted.chars().count() <= ERROR_TEXT_CHARS { return redacted; } diff --git a/crates/sqlbuild-core/src/redaction/main/redact_masked_text.rs b/crates/sqlbuild-core/src/redaction/main/redact_masked_text.rs new file mode 100644 index 0000000000..da69afe954 --- /dev/null +++ b/crates/sqlbuild-core/src/redaction/main/redact_masked_text.rs @@ -0,0 +1,10 @@ +//! `redact_masked_text`: exact masking and pattern redaction applied to text as one step. + +use crate::redaction::_helpers::patterns::named_redacted; +use crate::redaction::_helpers::readings::redacted_readings; + +/// `redact_text` after `mask`, with `mask` also applied to both readings of text with NUL. +#[must_use] +pub fn redact_masked_text(text: &str, mask: impl Fn(&str) -> String) -> String { + redacted_readings(text, |reading| named_redacted(&mask(reading))) +} diff --git a/crates/sqlbuild-core/src/redaction/main/redact_text.rs b/crates/sqlbuild-core/src/redaction/main/redact_text.rs index e80044a4f2..f260dca7e2 100644 --- a/crates/sqlbuild-core/src/redaction/main/redact_text.rs +++ b/crates/sqlbuild-core/src/redaction/main/redact_text.rs @@ -1,18 +1,10 @@ //! `redact_text`: obvious named secrets and URI passwords removed from diagnostic text. -use crate::redaction::_helpers::patterns::{ - AUTHORIZATION, BEARER, DDL_PASSWORD, SECRET_VALUE, URI_CREDENTIAL, substituted, -}; -use crate::redaction::constants::{ - BEARER_REPLACEMENT, DDL_REPLACEMENT, PAIR_REPLACEMENT, URI_REPLACEMENT, -}; +use crate::redaction::_helpers::patterns::named_redacted; +use crate::redaction::_helpers::readings::redacted_readings; -/// Authorization headers, bearer tokens, `name=value` secrets, SQL passwords, then URI passwords redacted. +/// Authorization headers, bearer tokens, `name=value` secrets, SQL passwords, then URI passwords redacted, in both readings of text with NUL. #[must_use] pub fn redact_text(value: &str) -> String { - let authorization: String = substituted(&AUTHORIZATION, value, PAIR_REPLACEMENT); - let bearer: String = substituted(&BEARER, &authorization, BEARER_REPLACEMENT); - let named: String = substituted(&SECRET_VALUE, &bearer, PAIR_REPLACEMENT); - let statement: String = substituted(&DDL_PASSWORD, &named, DDL_REPLACEMENT); - substituted(&URI_CREDENTIAL, &statement, URI_REPLACEMENT) + redacted_readings(value, named_redacted) } diff --git a/crates/sqlbuild-core/src/redaction/main/secret_field_name.rs b/crates/sqlbuild-core/src/redaction/main/secret_field_name.rs index 3895df24be..c092f4d2d0 100644 --- a/crates/sqlbuild-core/src/redaction/main/secret_field_name.rs +++ b/crates/sqlbuild-core/src/redaction/main/secret_field_name.rs @@ -2,9 +2,10 @@ use crate::redaction::constants::SECRET_FIELD_PARTS; -/// Whether the lowercased name, with `-` read as `_`, contains a secret field part. +/// Whether the lowercased name, without NUL and with `-` read as `_`, contains a secret field part. #[must_use] pub fn secret_field_name(name: &str) -> bool { - let lowered: String = name.to_lowercase().replace('-', "_"); + let mut lowered: String = name.to_lowercase().replace('-', "_"); + lowered.retain(|character| character != '\0'); SECRET_FIELD_PARTS.iter().any(|part| lowered.contains(part)) } diff --git a/crates/sqlbuild-core/src/redaction/tests.rs b/crates/sqlbuild-core/src/redaction/tests.rs index bb9efc8856..5483d72567 100644 --- a/crates/sqlbuild-core/src/redaction/tests.rs +++ b/crates/sqlbuild-core/src/redaction/tests.rs @@ -1,3 +1,5 @@ +#[path = "tests/helpers.rs"] +mod helpers; #[path = "tests/test_redact_text.rs"] mod redact_text; #[path = "tests/test_types.rs"] diff --git a/crates/sqlbuild-core/src/redaction/tests/helpers.rs b/crates/sqlbuild-core/src/redaction/tests/helpers.rs new file mode 100644 index 0000000000..5684fc2639 --- /dev/null +++ b/crates/sqlbuild-core/src/redaction/tests/helpers.rs @@ -0,0 +1,40 @@ +//! Shapes holding an obviously fake value, and NUL placed through them. + +pub(crate) const NAMED_SHAPES: [&str; 8] = [ + "password=zebraquokkawombat", + "pwd=zebraquokkawombat", + "api_key: zebraquokkawombat", + "Bearer zebraquokkawombat", + "Authorization: Basic zebraquokkawombat", + "PASSWORD 'zebraquokkawombat'", + "IDENTIFIED BY 'zebraquokkawombat'", + "postgres://orders:zebraquokkawombat@warehouse.local.test/orders", +]; +pub(crate) const ERROR_SHAPES: [&str; 9] = [ + "password=zebraquokkawombat", + "pwd=zebraquokkawombat", + "api_key: zebraquokkawombat", + "Bearer zebraquokkawombat", + "Authorization: Basic zebraquokkawombat", + "PASSWORD 'zebraquokkawombat'", + "IDENTIFIED BY 'zebraquokkawombat'", + "postgres://orders:zebraquokkawombat@warehouse.local.test/orders", + "postgres://orders:zebraquokkawombat", +]; +pub(crate) const SHAPE_LEADS: [&str; 5] = ["", "x", "17", "caf\u{e9}", "ValueError: refused "]; + +/// Whether any part of the fake value reads in `text`, with or without NUL. +pub(crate) fn shows_value(text: &str) -> bool { + let read: String = text.replace('\0', ""); + ["zebra", "quokka", "wombat"] + .iter() + .any(|part| read.contains(part)) +} + +/// `text` with one NUL at each character boundary. +pub(crate) fn nul_positions(text: &str) -> impl Iterator + '_ { + text.char_indices() + .map(|(index, _)| index) + .chain([text.len()]) + .map(|index| format!("{}\0{}", &text[..index], &text[index..])) +} diff --git a/crates/sqlbuild-core/src/redaction/tests/test_redact_text.rs b/crates/sqlbuild-core/src/redaction/tests/test_redact_text.rs index 6b7305b63e..b88968dbaf 100644 --- a/crates/sqlbuild-core/src/redaction/tests/test_redact_text.rs +++ b/crates/sqlbuild-core/src/redaction/tests/test_redact_text.rs @@ -1,6 +1,12 @@ +use crate::redaction::_helpers::patterns::{error_redacted, named_redacted}; use crate::redaction::main::redact_error_text::redact_error_text; +use crate::redaction::main::redact_masked_text::redact_masked_text; use crate::redaction::main::redact_text::redact_text; -use crate::redaction::tests::test_types::RedactTestCase; +use crate::redaction::main::secret_field_name::secret_field_name; +use crate::redaction::tests::helpers::{ + ERROR_SHAPES, NAMED_SHAPES, SHAPE_LEADS, nul_positions, shows_value, +}; +use crate::redaction::tests::test_types::{FieldNameTestCase, NulPositionTestCase, RedactTestCase}; #[test] fn given_diagnostic_text_when_redacting_then_matches_python_substitutions() { @@ -126,3 +132,156 @@ fn given_error_text_with_cut_uris_when_redacting_then_position_tells_a_port_from ); } } + +#[test] +fn given_error_text_with_nul_when_redacting_then_both_readings_apply() { + let test_cases = [ + RedactTestCase { + description: "a match only without NUL", + text: "pass\0word=example-fake-value refused", + expected_text: "[REDACTED]", + }, + RedactTestCase { + description: "a match only as it is", + text: "refused x\0Bearer example-fake-value", + expected_text: "[REDACTED]", + }, + RedactTestCase { + description: "a cut URI only as it is", + text: "refused 17\0postgres://orders:example-fake-value", + expected_text: "[REDACTED]", + }, + RedactTestCase { + description: "no match either way", + text: "refused \0order 17", + expected_text: "refused order 17", + }, + ]; + + for test_case in test_cases { + assert_eq!( + redact_error_text(test_case.text), + test_case.expected_text, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_masked_text_with_nul_when_redacting_then_the_mask_applies_to_both_readings() { + let test_cases = [ + RedactTestCase { + description: "a masked value only without NUL", + text: "refused zebra\0quokka", + expected_text: "[REDACTED]", + }, + RedactTestCase { + description: "a masked value beside NUL", + text: "refused \0zebraquokka", + expected_text: "[REDACTED]", + }, + RedactTestCase { + description: "nothing to mask", + text: "refused \0order 17", + expected_text: "refused order 17", + }, + RedactTestCase { + description: "text without NUL is only masked", + text: "refused zebraquokka", + expected_text: "refused ****", + }, + ]; + + for test_case in test_cases { + assert_eq!( + redact_masked_text(test_case.text, |reading| reading + .replace("zebraquokka", "****")), + test_case.expected_text, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_field_name_with_nul_when_classified_then_nul_is_ignored() { + let test_cases = [ + FieldNameTestCase { + description: "NUL inside the part", + name: "db_pass\0word", + expected_secret: true, + }, + FieldNameTestCase { + description: "NUL beside the separator", + name: "api\0-key", + expected_secret: true, + }, + FieldNameTestCase { + description: "an ordinary name", + name: "order\0_id", + expected_secret: false, + }, + ]; + + for test_case in test_cases { + assert_eq!( + secret_field_name(test_case.name), + test_case.expected_secret, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_shape_with_nul_at_any_position_when_redacting_then_it_matches_the_stricter_reading() { + let test_cases = [ + NulPositionTestCase { + description: "diagnostic text", + redact: redact_text, + reading: named_redacted, + shapes: &NAMED_SHAPES, + expected_exposed: 0, + }, + NulPositionTestCase { + description: "error text", + redact: redact_error_text, + reading: error_redacted, + shapes: &ERROR_SHAPES, + expected_exposed: 0, + }, + ]; + + for test_case in test_cases { + let (redact, reading) = (test_case.redact, test_case.reading); + let mut exposed: usize = 0; + for shape in test_case.shapes { + assert!( + !shows_value(&reading(shape)), + "a shape must redact: {shape}" + ); + assert_eq!( + redact(shape), + reading(shape), + "text without NUL is unchanged" + ); + for lead in SHAPE_LEADS { + let whole: String = format!("{lead}{shape}"); + exposed += nul_positions(&whole) + .filter(|text| { + let hidden: bool = + !shows_value(&reading(text)) || !shows_value(&reading(&whole)); + let redacted: String = redact(text); + (hidden && shows_value(&redacted)) || redacted.contains('\0') + }) + .count(); + } + } + assert_eq!( + exposed, test_case.expected_exposed, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-core/src/redaction/tests/test_types.rs b/crates/sqlbuild-core/src/redaction/tests/test_types.rs index 7466e971e7..c3f516738a 100644 --- a/crates/sqlbuild-core/src/redaction/tests/test_types.rs +++ b/crates/sqlbuild-core/src/redaction/tests/test_types.rs @@ -3,3 +3,18 @@ pub(crate) struct RedactTestCase { pub(crate) text: &'static str, pub(crate) expected_text: &'static str, } + +pub(crate) struct FieldNameTestCase { + pub(crate) description: &'static str, + pub(crate) name: &'static str, + pub(crate) expected_secret: bool, +} + +pub(crate) struct NulPositionTestCase { + pub(crate) description: &'static str, + pub(crate) redact: fn(&str) -> String, + /// The same redaction of a single reading. + pub(crate) reading: fn(&str) -> String, + pub(crate) shapes: &'static [&'static str], + pub(crate) expected_exposed: usize, +} diff --git a/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs b/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs index 5975edb91c..ba6d972ec4 100644 --- a/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs +++ b/crates/sqlbuild-core/src/screen_text/tests/test_screen_text.rs @@ -182,6 +182,28 @@ fn given_ready_rows_when_rendering_the_box_then_parts_wrap_between_labelled_line "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", ], }, + ReadyBoxTestCase { + description: "discovered sets add a row, each set after the first wrapping whole", + rows: vec![ + ui_row(), + BoxRow { + label: "Discovered".to_owned(), + parts: vec![ + "orders_plan 27 items".to_owned(), + "returns_plan \u{2717} ssh timeout (using last good, 11 items)".to_owned(), + ], + link: None, + }, + ], + columns: 80, + expected_rows: vec![ + "\u{256d}\u{2500} ready \u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256e}", + "\u{2502} UI http://127.0.0.1:8640 \u{2502}", + "\u{2502} Discovered orders_plan 27 items \u{2502}", + "\u{2502} returns_plan \u{2717} ssh timeout (using last good, 11 items) \u{2502}", + "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", + ], + }, ReadyBoxTestCase { description: "a part wider than the box starts its own line and wraps by words", rows: vec![BoxRow { diff --git a/crates/sqlbuild-discovery/src/project_validation/_helpers/identities.rs b/crates/sqlbuild-discovery/src/project_validation/_helpers/identities.rs index 5938487a72..bf47fce410 100644 --- a/crates/sqlbuild-discovery/src/project_validation/_helpers/identities.rs +++ b/crates/sqlbuild-discovery/src/project_validation/_helpers/identities.rs @@ -64,6 +64,14 @@ impl<'a> Candidates<'a> { } } +/// The name a node's author wrote: `asset` for a discovered item's node `asset[item]`. +fn authored_name(name: &str) -> &str { + match name.split_once('[') { + Some((asset, item)) if item.ends_with(']') => asset, + _ => name, + } +} + /// Reject the first identity that is not canonical lowercase snake_case. pub(crate) fn validate_identities(facts: &ProjectFacts) -> Result<(), ValidationFailure> { for candidate in candidates(facts) { @@ -133,7 +141,7 @@ fn candidates(facts: &ProjectFacts) -> Vec> { candidates.push_named(&facts.materializations, "materialization"); for kind in [NodeKind::Loader, NodeKind::Asset, NodeKind::Check] { for node in facts.nodes.iter().filter(|node| node.kind == kind) { - candidates.push(&node.name, kind.label(), &node.path); + candidates.push(authored_name(&node.name), kind.label(), &node.path); } } candidates.push_named(&facts.hook_functions, "Python hook"); diff --git a/crates/sqlbuild-host/src/entries/_helpers/executor.rs b/crates/sqlbuild-host/src/entries/_helpers/executor.rs index 453758fbe4..dce3fc7ba2 100644 --- a/crates/sqlbuild-host/src/entries/_helpers/executor.rs +++ b/crates/sqlbuild-host/src/entries/_helpers/executor.rs @@ -714,6 +714,11 @@ pub(crate) const ENTRIES: &[HostEntry] = &[ kind: HostKind::Function, edge: HostEdge::Executor, }, + HostEntry { + name: "statement_activity", + kind: HostKind::Function, + edge: HostEdge::Executor, + }, HostEntry { name: "EventDispatcher", kind: HostKind::Class, diff --git a/crates/sqlbuild-host/src/entries/_helpers/user_code.rs b/crates/sqlbuild-host/src/entries/_helpers/user_code.rs index 7a1feec3c2..4d90ecd389 100644 --- a/crates/sqlbuild-host/src/entries/_helpers/user_code.rs +++ b/crates/sqlbuild-host/src/entries/_helpers/user_code.rs @@ -284,4 +284,19 @@ pub(crate) const ENTRIES: &[HostEntry] = &[ kind: HostKind::Function, edge: HostEdge::UserCode, }, + HostEntry { + name: "read_discover_definition", + kind: HostKind::Function, + edge: HostEdge::UserCode, + }, + HostEntry { + name: "discovered_result_json", + kind: HostKind::Function, + edge: HostEdge::UserCode, + }, + HostEntry { + name: "item_dependency_refs", + kind: HostKind::Function, + edge: HostEdge::UserCode, + }, ]; diff --git a/crates/sqlbuild-host/src/entries/models.rs b/crates/sqlbuild-host/src/entries/models.rs index ad017649d6..e993faf7a2 100644 --- a/crates/sqlbuild-host/src/entries/models.rs +++ b/crates/sqlbuild-host/src/entries/models.rs @@ -185,6 +185,9 @@ pub enum UserCodeHost { RunCommandOutputSinks, GetLifecycleEventSinkDefinition, InvokeRecallSink, + ReadDiscoverDefinition, + DiscoveredResultJson, + ItemDependencyRefs, } impl UserCodeHost { @@ -348,6 +351,7 @@ pub enum ExecutorHost { ExecutionDeadlinesSuspended, AuditEvidenceScope, CancelRunningStatements, + StatementActivity, EventDispatcher, OperationLifecycle, StatementLifecycle, diff --git a/crates/sqlbuild-host/src/models.rs b/crates/sqlbuild-host/src/models.rs index 2fa6ef06b3..af745cb10b 100644 --- a/crates/sqlbuild-host/src/models.rs +++ b/crates/sqlbuild-host/src/models.rs @@ -429,6 +429,28 @@ pub struct BuildExecutionTimings { pub struct LifeCycleEvent { pub kind: LifeCycleEventKind, pub content: String, + /// The level of a `ctx.log` line; SQL events have none. + pub level: Option, +} + +/// The level of a line a node logs with `ctx.log`. Mirrors `sqlbuild.adapter.contract.types.LogLevel`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LogLevel { + Info, + Warning, + Error, +} + +impl ResultEnum for LogLevel { + const ALL: &'static [Self] = &[Self::Info, Self::Warning, Self::Error]; + + fn value(self) -> &'static str { + match self { + Self::Info => "info", + Self::Warning => "warning", + Self::Error => "error", + } + } } /// One pre- or post-hook of a model. Mirrors `sqlbuild.executor.run.models.HookExecutionResult`. @@ -508,6 +530,7 @@ pub struct ModelExecutionResult { pub batch_count: Option, pub batch_size: Option, pub rows_affected: Option, + pub table_rows: Option, pub cursor_range_start: Option, pub cursor_range_end: Option, pub cursor_type: Option, @@ -587,6 +610,7 @@ pub struct LoadExecutionResult { pub resource_kind: ExecutionResourceKind, pub staging_relation: Option, pub rows_loaded: i64, + pub rows_affected: Option, pub duration_ms: Option, pub lifecycle_events: Vec, pub skip_mode: Option, diff --git a/crates/sqlbuild-orchestration/Cargo.toml b/crates/sqlbuild-orchestration/Cargo.toml index 88bf4e2af2..1cea2a9072 100644 --- a/crates/sqlbuild-orchestration/Cargo.toml +++ b/crates/sqlbuild-orchestration/Cargo.toml @@ -19,6 +19,7 @@ croner.workspace = true flate2.workspace = true futures-util.workspace = true getrandom.workspace = true +object_store.workspace = true openidconnect.workspace = true reqwest.workspace = true rusqlite.workspace = true @@ -41,6 +42,7 @@ toml.workspace = true tower-http.workspace = true utoipa.workspace = true uuid.workspace = true +zstd.workspace = true [dev-dependencies] axum-server.workspace = true diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs index 48c580fff2..ba8eec4603 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs @@ -1,6 +1,6 @@ //! Authenticate machine bearers before buffering; scope checks stay in each owning endpoint. -use std::net::SocketAddr; +use std::sync::Arc; use axum::extract::{Request, State}; use axum::http::{HeaderMap, StatusCode, header}; @@ -10,7 +10,7 @@ use uuid::Uuid; use crate::api::_helpers::authentication::password_transport::private_cache_control; use crate::api::errors::ApiError; -use crate::api::models::{DevelopmentScope, ReadResource}; +use crate::api::models::{DevelopmentAuthorities, DevelopmentScope, ReadResource}; use crate::credentials::main::tokens::authenticate_token::authenticate_token; use crate::credentials::models::{CredentialScope, TokenIdentity}; use crate::store::main::{begin::begin, commit::commit, query::query}; @@ -64,21 +64,24 @@ fn unauthorized() -> ApiError { /// Reject browser cross-origin and DNS-rebinding requests on the disabled-auth listener. pub(crate) async fn local_request( - State(address): State, + State(accepted): State>, request: Request, next: Next, ) -> Result { - let authorities = [address.to_string(), format!("localhost:{}", address.port())]; let valid_host = request.headers().get(header::HOST).is_some_and(|value| { - value - .to_str() - .is_ok_and(|host| authorities.iter().any(|allowed| host == allowed)) + value.to_str().is_ok_and(|host| { + accepted + .hosts + .iter() + .any(|allowed| host.eq_ignore_ascii_case(allowed)) + }) }); let valid_origin = request.headers().get(header::ORIGIN).is_none_or(|value| { value.to_str().is_ok_and(|origin| { - authorities + accepted + .origins .iter() - .any(|host| origin == format!("http://{host}")) + .any(|allowed| origin.eq_ignore_ascii_case(allowed)) }) }); if !valid_host || !valid_origin { diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/cli_login.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/cli_login.rs index 58f1a88533..fd9d81c56c 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/cli_login.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/cli_login.rs @@ -18,7 +18,8 @@ use crate::credentials::main::cli_login::{ approve_login::approve_login, claim_login::claim_login, start_login::start_login, }; use crate::credentials::models::{ - AuditContext, AuthenticatedPerson, AuthenticationAttempt, ClaimedLogin, StartedLogin, + AuditContext, AuthenticatedPerson, AuthenticationAttempt, ClaimedLogin, ServiceKeyIdentity, + StartedLogin, }; use crate::store::models::ControlStore; @@ -80,14 +81,16 @@ pub(crate) async fn start( responses((status = 204), (status = 401, body = AuthenticationDenial)))] pub(crate) async fn approve( State(store): State, - (Extension(context), Extension(person)): ( + (Extension(context), Extension(person), service_account): ( Extension, Extension, + Option>, ), headers: HeaderMap, Json(request): Json, ) -> Result { - if !session_header(&headers) + if service_account.is_none() + && !session_header(&headers) && approve_login( &store, &context, diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs index abbc7b8872..864d7df517 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/configure.rs @@ -2,9 +2,13 @@ use std::net::SocketAddr; +use axum::routing::get; use axum::{Extension, Router, middleware}; -use crate::api::_helpers::authentication::{development, oidc, password_sessions, trusted_proxy}; +use crate::api::_helpers::authentication::proxy_warnings::warn_plain_http_keys; +use crate::api::_helpers::authentication::{ + development, oidc, password_sessions, service_keys, trusted_proxy, +}; use crate::api::models::{ApiAuthentication, DevelopmentScope, GroupRole, HumanLogin, LoginMode}; use crate::store::errors::ControlError; use crate::store::models::ControlStore; @@ -28,16 +32,30 @@ pub(crate) async fn configure( HumanLogin::Oidc(settings) => settings.group_roles.clone(), _ => Vec::new(), }; + let origin = match &login { + HumanLogin::Password(origin) => Some(origin.as_str()), + HumanLogin::TrustedProxy(settings) => Some(settings.origin.as_str()), + HumanLogin::Oidc(settings) => Some(settings.origin.as_str()), + HumanLogin::None | HumanLogin::Development(_) => None, + }; + if !matches!(login, HumanLogin::Development(_)) { + warn_plain_http_keys(address, origin); + } let login_mode = match &login { HumanLogin::Oidc(_) => LoginMode::Oidc, HumanLogin::TrustedProxy(_) => LoginMode::TrustedProxy, HumanLogin::Development(_) => LoginMode::Disabled, - _ => LoginMode::Password, + HumanLogin::None => LoginMode::Keys, + HumanLogin::Password(_) => LoginMode::Password, }; let (development, routes) = match login { - HumanLogin::None => (None, Router::new()), + HumanLogin::None => ( + None, + service_keys::key_only(store, password_sessions::person_routes()) + .route("/api/auth/login-mode", get(service_keys::keys_only_mode)), + ), HumanLogin::Development(scope) => { - if !address.ip().is_loopback() { + if !address.ip().is_loopback() && !scope.listens_beyond_loopback { return Err(ControlError::Invalid( "disabled authentication requires a loopback listener".into(), )); diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs index 03f024d94c..defea4ca9e 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development.rs @@ -1,4 +1,4 @@ -//! Development person requests: `local_request` already confined them to a loopback host and origin. +//! Development person requests: `local_request` already confined them to an accepted host and origin. use std::net::SocketAddr; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development_hosts.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development_hosts.rs new file mode 100644 index 0000000000..65aada3a3d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/development_hosts.rs @@ -0,0 +1,58 @@ +//! The `Host` and `Origin` values a sign-in-free development listener accepts. + +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + +use crate::api::constants::{HTTP_PORT, HTTP_SCHEME, HTTPS_PORT, HTTPS_SCHEME, LOOPBACK_HOST}; +use crate::api::models::DevelopmentAuthorities; + +/// The listener's local names, then each allowed name on its own port, or on the listener's and the default ports. +pub(crate) fn development_authorities( + address: SocketAddr, + allowed: &[String], +) -> DevelopmentAuthorities { + let port: u16 = address.port(); + let mut hosts: Vec = match address.ip() { + IpAddr::V4(ip) if ip.is_unspecified() => vec![Ipv4Addr::LOCALHOST.into()], + IpAddr::V6(ip) if ip.is_unspecified() => { + vec![Ipv6Addr::LOCALHOST.into(), Ipv4Addr::LOCALHOST.into()] + } + ip => vec![ip], + } + .into_iter() + .map(|ip: IpAddr| SocketAddr::new(ip, port).to_string()) + .collect(); + hosts.push(format!("{LOOPBACK_HOST}:{port}")); + let mut origins: Vec = hosts + .iter() + .map(|host| format!("{HTTP_SCHEME}://{host}")) + .collect(); + for entry in allowed.iter().map(|entry| entry.to_ascii_lowercase()) { + let (name, only): (&str, Option) = split_port(&entry); + let ports: Vec = + only.map_or_else(|| vec![port, HTTP_PORT, HTTPS_PORT], |only| vec![only]); + for port in ports { + let full: String = format!("{name}:{port}"); + for (scheme, default) in [(HTTP_SCHEME, HTTP_PORT), (HTTPS_SCHEME, HTTPS_PORT)] { + if port == default { + hosts.push(name.to_owned()); + origins.push(format!("{scheme}://{name}")); + } else if port != HTTP_PORT && port != HTTPS_PORT { + origins.push(format!("{scheme}://{full}")); + } + } + hosts.push(full); + } + } + DevelopmentAuthorities { hosts, origins } +} + +/// `name:port` apart; a bracketed IPv6 address without a port has none. +fn split_port(entry: &str) -> (&str, Option) { + match entry + .rsplit_once(':') + .map(|(name, port)| (name, port.parse())) + { + Some((name, Ok(port))) => (name, Some(port)), + _ => (entry, None), + } +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs index ef181ccbeb..d73087aa2d 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod bearer; pub(crate) mod cli_login; pub(crate) mod configure; pub(crate) mod development; +pub(crate) mod development_hosts; pub(crate) mod oidc; pub(crate) mod oidc_provider; pub(crate) mod origins; @@ -9,4 +10,5 @@ pub(crate) mod password_sessions; pub(crate) mod password_transport; pub(crate) mod proxy_settings; pub(crate) mod proxy_warnings; +pub(crate) mod service_keys; pub(crate) mod trusted_proxy; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs index 86f5bc7586..e46e0fd342 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs @@ -32,9 +32,11 @@ use crate::store::models::{ControlStore, TransactionMode}; /// Session-authenticated person routes, plus routes acting on the caller's own session. pub(crate) fn protected(store: &ControlStore) -> Router { - person_routes() - .route_layer(middleware::from_fn_with_state(store.clone(), authenticate)) - .merge(session_routes(store)) + super::service_keys::keyed( + store, + person_routes().route_layer(middleware::from_fn_with_state(store.clone(), authenticate)), + ) + .merge(session_routes(store)) } /// Routes that act on the caller's own session. @@ -74,6 +76,27 @@ pub(crate) fn person_routes() -> Router { "/api/admin/server", get(crate::api::_helpers::resources::administrators::server), ) + .route( + "/api/admin/service-accounts", + get(crate::api::_helpers::resources::service_accounts::list) + .post(crate::api::_helpers::resources::service_accounts::create), + ) + .route( + "/api/admin/service-accounts/{principal_id}/keys", + post(crate::api::_helpers::resources::service_accounts::rotate), + ) + .route( + "/api/admin/service-accounts/{principal_id}/keys/{key_id}/revoke", + post(crate::api::_helpers::resources::service_accounts::revoke), + ) + .route( + "/api/admin/service-accounts/{principal_id}/disabled", + post(crate::api::_helpers::resources::service_accounts::disable), + ) + .route( + "/api/admin/service-accounts/{principal_id}/role", + post(crate::api::_helpers::resources::service_accounts::role), + ) .route( "/api/admin/locations/{location_id}/targets/{target}/roles", get(crate::api::_helpers::resources::administrators::definitions), @@ -115,6 +138,18 @@ pub(crate) fn person_routes() -> Router { "/api/control/locations/{location_id}/targets/{target}/warehouse-syncs", post(crate::api::_helpers::resources::person_location_work::request_sync), ) + .route( + "/api/control/locations/{location_id}/targets/{target}/republish", + post(crate::api::_helpers::resources::person_republish::request), + ) + .route( + "/api/control/locations/{location_id}/targets/{target}/republish/{request_id}", + get(crate::api::_helpers::resources::person_republish::read), + ) + .route( + "/api/control/locations/{location_id}/targets/{target}/discovered", + get(crate::api::_helpers::resources::person_republish::discovered), + ) .route( "/api/control/locations/{location_id}/targets/{target}/connection-tests/{request_id}", get(crate::api::_helpers::resources::person_location_work::result), @@ -273,6 +308,22 @@ pub(crate) fn person_routes() -> Router { "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output", get(crate::api::_helpers::resources::person_reads::run_output), ) + .route( + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/index", + get(crate::api::_helpers::resources::person_reads::run_output_index), + ) + .route( + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/lines", + get(crate::api::_helpers::resources::person_reads::run_output_lines), + ) + .route( + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/search", + get(crate::api::_helpers::resources::person_reads::run_output_search), + ) + .route( + "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/download", + get(crate::api::_helpers::resources::person_reads::run_output_download), + ) .route( "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/nodes/{node_key}/error", get(crate::api::_helpers::resources::person_reads::run_node_error), diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs index 930b37c4e0..1f2980695b 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs @@ -10,6 +10,8 @@ use axum::{Extension, Json}; use uuid::Uuid; use crate::api::_helpers::authentication::proxy_settings::ProxySettings; +use crate::api::_helpers::authentication::service_keys::presented_key; + use crate::api::constants::{ EVENT_STREAM_MEDIA_TYPE, PASSWORD_COOKIE, PASSWORD_CSRF_COOKIE, PASSWORD_CSRF_HEADER, STREAM_BUFFERING_HEADER, STREAM_CACHE_CONTROL, @@ -18,10 +20,15 @@ use crate::api::errors::ApiError; use crate::api::models::{AuthenticationDenial, BrowserOrigin, ExternalIdentityResponse}; use crate::credentials::constants::PASSWORD_SESSION_SECONDS; use crate::credentials::main::sessions::authenticate_session::authenticate_session; -use crate::credentials::models::{AuditContext, AuthenticatedPerson, IssuedSession, SessionAccess}; +use crate::credentials::models::{ + AuditContext, AuthenticatedPerson, IssuedSession, ServiceKeyIdentity, SessionAccess, +}; use crate::store::errors::ControlError; use crate::store::models::ControlStore; +/// The sign-in and session routes, which never accept a service key. +const SIGN_IN_ROUTES: &str = "/api/auth/"; + /// Refuses a trusted peer under another site's `Host`, as a DNS-rebinding page sends, then checks writes. pub(crate) async fn guard( Extension(origin): Extension, @@ -48,7 +55,8 @@ pub(crate) async fn guard( .get::>() .filter(|settings| settings.trusted_peers.contains(&peer.ip().to_canonical())) .cloned(); - if let Some(settings) = &proxy { + let keyed = keyed_caller(&request); + if let Some(settings) = proxy.as_ref().filter(|_| !keyed) { let host = single_header(request.headers(), header::HOST.as_str()); if !settings.host_allowed(host) { settings.note_refused_host(host, peer.ip().to_canonical()); @@ -61,7 +69,9 @@ pub(crate) async fn guard( }); } } - let allowed: bool = if proxy.is_some() { + let allowed: bool = if keyed { + true + } else if proxy.is_some() { proxy_request_allowed(&request, &origin) } else { browser_request_allowed(&request, &origin) @@ -80,6 +90,11 @@ pub(crate) async fn guard( Ok(response) } +/// A keyed script outside sign-in routes; no page sends a key cross-site, as the server never grants CORS. +fn keyed_caller(request: &Request) -> bool { + presented_key(request.headers()).is_some() && !request.uri().path().starts_with(SIGN_IN_ROUTES) +} + /// A browser request for this origin's host whose write, if any, comes from the origin itself. fn browser_request_allowed(request: &Request, origin: &BrowserOrigin) -> bool { let authority: Option<&str> = origin.0.split_once("://").map(|(_, authority)| authority); @@ -129,6 +144,9 @@ pub(crate) async fn authenticate( mut request: Request, next: Next, ) -> Result { + if request.extensions().get::().is_some() { + return Ok(next.run(request).await); + } let context = request .extensions() .get::() diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs index d2a5d2f39b..723fbcf78d 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs @@ -1,6 +1,6 @@ -//! Operator warnings a trusted proxy setup prints on stderr; an untrusted peer's header values are never printed. +//! Operator warnings sign-in setups print on stderr; an untrusted peer's header values are never printed. -use std::net::IpAddr; +use std::net::{IpAddr, SocketAddr}; use crate::api::constants::PROXY_NOTED_SOURCES; @@ -11,6 +11,18 @@ pub(crate) fn warn_plain_http_origin(origin: &str) { ); } +/// Warns when service keys can reach a network listener over plain HTTP: no origin, or an `http://` one. +pub(crate) fn warn_plain_http_keys(address: SocketAddr, origin: Option<&str>) { + if address.ip().is_loopback() || origin.is_some_and(|origin| origin.starts_with("https://")) { + return; + } + eprintln!( + "warning: the server accepts service account keys on {address} over plain HTTP, so a key \ + sent there crosses the network unencrypted; terminate TLS in front of this listener and \ + give scripts its https:// URL" + ); +} + pub(crate) fn warn_untrusted_source(header: &str, peer: IpAddr) { eprintln!( "warning: ignored the trusted-proxy username header {header} from {peer}, which is not in \ diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/service_keys.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/service_keys.rs new file mode 100644 index 0000000000..40112b09b0 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/service_keys.rs @@ -0,0 +1,169 @@ +//! A service account's key authenticates person routes from any peer, whatever the sign-in mode. + +use std::net::SocketAddr; +use std::time::{Duration, Instant}; + +use axum::Json; +use axum::Router; +use axum::extract::{ConnectInfo, Request, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::middleware::{self, Next}; +use axum::response::Response; +use chrono::{DateTime, Utc}; +use uuid::Uuid; + +use crate::api::_helpers::authentication::password_transport::{ + deny, private_cache_control, single_header, +}; +use crate::api::errors::ApiError; +use crate::api::models::{KeyRefusals, LoginMode, LoginModeAnswer}; +use crate::credentials::constants::{KEY_REFUSAL_INTERVAL_SECONDS, SERVICE_KEY_PREFIX}; +use crate::credentials::main::service_keys::authenticate_service_key::authenticate_service_key; +use crate::credentials::main::service_keys::record_refused_key::record_refused_key; +use crate::credentials::main::service_keys::record_service_key_use::record_service_key_use; +use crate::credentials::models::{ + AuditContext, AuthenticatedPerson, DefaultRole, ServiceKeyCheck, ServiceKeyIdentity, +}; +use crate::store::models::ControlStore; + +/// Forget refusals beyond this many keys; at worst a refusal is audited again sooner. +const REFUSALS_KEPT: usize = 10_000; + +/// The key in a single `Authorization: Bearer sqbk_…` header; a proxy's own bearer token is no key. +pub(crate) fn presented_key(headers: &HeaderMap) -> Option<&str> { + single_header(headers, header::AUTHORIZATION.as_str())? + .strip_prefix("Bearer ") + .filter(|credential| credential.starts_with(SERVICE_KEY_PREFIX)) +} + +/// `routes`, also open to service keys; a request without one goes on to the mode's own sign-in. +pub(crate) fn keyed(store: &ControlStore, routes: Router) -> Router { + let state = (store.clone(), KeyRefusals::default()); + routes.route_layer(middleware::from_fn_with_state(state, optional)) +} + +/// `routes` on a server without people's sign-in: only service keys get in. +pub(crate) fn key_only(store: &ControlStore, routes: Router) -> Router { + let state = (store.clone(), KeyRefusals::default()); + routes.route_layer(middleware::from_fn_with_state(state, required)) +} + +async fn optional( + State(state): State<(ControlStore, KeyRefusals)>, + request: Request, + next: Next, +) -> Result { + match presented_key(request.headers()).map(str::to_owned) { + Some(key) => keyed_request(&state, (request, next), &key).await, + None => Ok(next.run(request).await), + } +} + +async fn required( + State(state): State<(ControlStore, KeyRefusals)>, + request: Request, + next: Next, +) -> Result { + let mut response = match presented_key(request.headers()).map(str::to_owned) { + Some(key) => keyed_request(&state, (request, next), &key).await?, + None => deny(&context_of(&request))?, + }; + private_cache_control(&mut response); + response.headers_mut().insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + Ok(response) +} + +/// Runs the request as the key's service account, without the default role; a known key refused is audited. +async fn keyed_request( + (store, refusals): &(ControlStore, KeyRefusals), + (mut request, next): (Request, Next), + key: &str, +) -> Result { + let mut context = context_of(&request); + let now = Utc::now(); + match authenticate_service_key(store, key, now).await? { + ServiceKeyCheck::Accepted(identity) => { + context.actor = format!("principal:{}", identity.principal_id); + context.granting_role = "service-key".into(); + let extensions = request.extensions_mut(); + extensions.insert(context); + extensions.insert(AuthenticatedPerson(identity.principal_id, None)); + extensions.insert(DefaultRole::None); + extensions.insert(identity); + let response = next.run(request).await; + note_use(store, (identity, response.status()), now).await; + Ok(response) + } + ServiceKeyCheck::Refused { + principal_id, + key_id, + reason, + } => { + if refusal_due(refusals, key_id) { + record_refused_key(store, &context, (principal_id, key_id, reason)).await?; + } + deny(&context) + } + ServiceKeyCheck::Unknown => deny(&context), + } +} + +/// Moves the key's last use for a request that wasn't refused; a failed write never fails the call it describes. +async fn note_use( + store: &ControlStore, + (identity, status): (ServiceKeyIdentity, StatusCode), + now: DateTime, +) { + if !matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) { + drop(record_service_key_use(store, identity, now).await); + } +} + +/// The sign-in guard's context, or one built from the socket peer where no guard ran. +fn context_of(request: &Request) -> AuditContext { + request + .extensions() + .get::() + .cloned() + .unwrap_or_else(|| AuditContext { + actor: "anonymous".into(), + granting_role: "authentication".into(), + request_id: Uuid::now_v7(), + ip_address: request + .extensions() + .get::>() + .map(|ConnectInfo(peer)| peer.ip().to_canonical()), + }) +} + +/// Whether `key_id`'s refusal is audited now: at most once an interval, so a retrying script can't flood the log. +fn refusal_due(refusals: &KeyRefusals, key_id: Uuid) -> bool { + let Ok(mut seen) = refusals.0.lock() else { + return true; + }; + let now = Instant::now(); + let interval = Duration::from_secs(KEY_REFUSAL_INTERVAL_SECONDS); + if seen + .get(&key_id) + .is_some_and(|last| now.duration_since(*last) < interval) + { + return false; + } + if seen.len() >= REFUSALS_KEPT { + seen.clear(); + } + seen.insert(key_id, now); + true +} + +#[utoipa::path(get, path = "/api/auth/login-mode", operation_id = "readLoginMode", + description = "Answered only by a server without sign-in for people, so a browser or sqb login can say so instead of offering a password.", + responses((status = 200, body = LoginModeAnswer), (status = 404, description = "People sign in on this server")))] +pub(crate) async fn keys_only_mode() -> Json { + Json(LoginModeAnswer { + login_mode: LoginMode::Keys, + }) +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs index 0fc14f1dcb..170901bf7a 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/trusted_proxy.rs @@ -13,6 +13,7 @@ use crate::api::_helpers::authentication::password_sessions; use crate::api::_helpers::authentication::password_transport::{self, deny, guard, single_header}; use crate::api::_helpers::authentication::proxy_settings::{ProxySettings, canonical_username}; use crate::api::_helpers::authentication::proxy_warnings::warn_plain_http_origin; +use crate::api::_helpers::authentication::service_keys; use crate::api::constants::HTTP_SCHEME; use crate::api::errors::ApiError; use crate::api::models::{ @@ -20,7 +21,7 @@ use crate::api::models::{ }; use crate::authorization::main::people::resolve_proxy_person::resolve_proxy_person; use crate::authorization::models::ProxyPerson; -use crate::credentials::models::{AuditContext, AuthenticatedPerson}; +use crate::credentials::models::{AuditContext, AuthenticatedPerson, ServiceKeyIdentity}; use crate::store::errors::ControlError; use crate::store::models::ControlStore; @@ -34,10 +35,11 @@ pub(crate) fn router( warn_plain_http_origin(&origin.0); } let mut routes = Router::new() - .merge( + .merge(service_keys::keyed( + store, password_sessions::person_routes() .route_layer(middleware::from_fn_with_state(store.clone(), authenticate)), - ) + )) .merge(password_sessions::session_routes(store)) .merge(super::cli_login::router(BrowserLoginMethod::Proxy)) .layer(middleware::from_fn(guard)) @@ -74,6 +76,9 @@ async fn authenticate( mut request: Request, next: Next, ) -> Result { + if request.extensions().get::().is_some() { + return Ok(next.run(request).await); + } if password_transport::session_header(request.headers()) { return password_transport::authenticate(State(store), request, next).await; } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs index 34d5a9dace..3b6e7875f1 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs @@ -7,6 +7,7 @@ use tokio::sync::{broadcast, watch}; use tower_http::compression::CompressionLayer; use crate::api::_helpers::authentication::bearer::local_request; +use crate::api::_helpers::authentication::development_hosts::development_authorities; use crate::api::_helpers::resources::compression::compress_reads_only; use crate::api::_helpers::resources::router::router; use crate::api::_helpers::resources::server_errors::generic_server_errors; @@ -34,7 +35,7 @@ pub(crate) fn application_router( .with_state(store.clone()) } -/// The development UI, the local-only guard of a development scope, and the response layers. +/// The development UI, the Host and Origin guard of a development scope, and the response layers. pub(crate) fn development_application( application: Router, scope: Option, @@ -42,9 +43,12 @@ pub(crate) fn development_application( ) -> Router { let application = serve_ui(application, UI_ASSETS); let application = match scope { - Some(scope) => application - .layer(Extension(scope)) - .layer(middleware::from_fn_with_state(address, local_request)), + Some(scope) => { + let accepted = Arc::new(development_authorities(address, &scope.allowed_hosts)); + application + .layer(Extension(scope)) + .layer(middleware::from_fn_with_state(accepted, local_request)) + } None => application, }; application diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs index 7e54286aec..6722f3cc50 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs @@ -17,6 +17,7 @@ pub(crate) mod person_node_sql; pub(crate) mod person_operations; pub(crate) mod person_plans; pub(crate) mod person_reads; +pub(crate) mod person_republish; pub(crate) mod person_selection; pub(crate) mod plain_http; pub(crate) mod request_json; @@ -24,6 +25,7 @@ pub(crate) mod router; pub(crate) mod run_reads; pub(crate) mod runs; pub(crate) mod server_errors; +pub(crate) mod service_accounts; pub(crate) mod snapshots; pub(crate) mod trigger_reads; pub(crate) mod ui_assets; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs index 2745a039c0..8f6f33e738 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs @@ -1,13 +1,14 @@ //! Person reads of run nodes and their errors, node run history, catalog nodes, jobs and one job's declaration, triggers, ticks and publications; refusal precedes every lookup, so unknown objects look forbidden. use axum::extract::{Path, Query, State}; -use axum::http::{HeaderMap, StatusCode}; -use axum::response::Response; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; use axum::{Extension, Json}; use serde::Deserialize; use uuid::Uuid; use crate::api::_helpers::resources::cached_json::cached_json; +use crate::api::_helpers::resources::runs::no_output_store; use crate::api::errors::ApiError; use crate::api::models::BrowserOrigin; use crate::api::models::{ @@ -32,6 +33,14 @@ use crate::platform::main::person_reads::read_person_problems::read_person_probl use crate::platform::models::{ LocationHealthObservation, PersonPlatformEventPage, PlatformProblems, }; +use crate::run_output::main::download_person_output::download_person_output; +use crate::run_output::main::read_person_output_index::read_person_output_index; +use crate::run_output::main::read_person_output_page::read_person_output_page; +use crate::run_output::main::search_person_output::search_person_output; +use crate::run_output::models::{ + OutputDownloadQuery, OutputIndexQuery, OutputPage, OutputPageQuery, OutputSearch, + OutputSearchQuery, OutputStream, RunOutputIndex, +}; use crate::runs::main::listings::list_person_run_nodes::list_person_run_nodes; use crate::runs::models::{ NodeRunRecord, RunEventRecord, RunIgnoredAuditFailure, RunNodeFailure, RunNodeRecord, @@ -57,6 +66,7 @@ use crate::warehouse_history::main::read_person_run_statement_sql::read_person_r use crate::warehouse_history::main::read_person_run_statements::read_person_run_statements; use crate::warehouse_history::models::{CostSummaryRecord, NodeCostRecord}; use crate::warehouse_metadata::models::{CatalogNodeRecord, WarehouseResourceCostRecord}; +use futures_util::StreamExt; /// Default and largest cost window, in days. const COST_DAYS: (u32, u32) = (7, 90); @@ -392,6 +402,163 @@ pub(crate) async fn run_output( .ok_or_else(|| not_found("run not found")) } +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/index", operation_id = "readPersonRunOutputIndex", + params(("location_id" = Uuid, Path), ("target" = String, Path), ("run_id" = Uuid, Path), OutputIndexQuery), + responses((status = 200, body = RunOutputIndex), (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody, description = "Needs view.evidence on every node the run selected"), + (status = 404, description = "Run not found for a person who may view the whole target")), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn run_output_index( + (State(store), Extension(context)): (State, Extension), + Extension(default_role): Extension, + (Path((location_id, target, run_id)), Query(query)): ( + Path<(Uuid, String, Uuid)>, + Query, + ), + Extension(AuthenticatedPerson(principal, _)): Extension, +) -> Result, ApiError> { + read_person_output_index( + &store, + ( + (&context, principal), + (location_id, &target, run_id), + default_role, + ), + query.node.as_deref(), + ) + .await? + .map(Json) + .ok_or_else(|| not_found("run not found")) +} + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/lines", operation_id = "readPersonRunOutputLines", + params(("location_id" = Uuid, Path), ("target" = String, Path), ("run_id" = Uuid, Path), OutputPageQuery), + responses((status = 200, body = OutputPage), (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody, description = "Needs view.evidence on every node the run selected"), + (status = 404, description = "Run not found for a person who may view the whole target"), + (status = 503, body = crate::api::models::ApiErrorBody, description = "The server keeps no run output")), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn run_output_lines( + (State(store), Extension(context), Extension(facts)): ( + State, + Extension, + Extension, + ), + Extension(default_role): Extension, + (Path((location_id, target, run_id)), Query(query)): ( + Path<(Uuid, String, Uuid)>, + Query, + ), + Extension(AuthenticatedPerson(principal, _)): Extension, +) -> Result, ApiError> { + let output = facts.output.ok_or_else(no_output_store)?; + read_person_output_page( + &store, + &output, + ( + (&context, principal), + (location_id, &target, run_id), + default_role, + ), + &query, + ) + .await? + .map(Json) + .ok_or_else(|| not_found("run not found")) +} + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/search", operation_id = "searchPersonRunOutput", + params(("location_id" = Uuid, Path), ("target" = String, Path), ("run_id" = Uuid, Path), OutputSearchQuery), + responses((status = 200, body = OutputSearch), (status = 400, body = crate::api::models::ApiErrorBody, description = "Empty search text"), + (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody, description = "Needs view.evidence on every node the run selected"), + (status = 404, description = "Run not found for a person who may view the whole target"), + (status = 503, body = crate::api::models::ApiErrorBody, description = "The server keeps no run output")), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn run_output_search( + (State(store), Extension(context), Extension(facts)): ( + State, + Extension, + Extension, + ), + Extension(default_role): Extension, + (Path((location_id, target, run_id)), Query(query)): ( + Path<(Uuid, String, Uuid)>, + Query, + ), + Extension(AuthenticatedPerson(principal, _)): Extension, +) -> Result, ApiError> { + let output = facts.output.ok_or_else(no_output_store)?; + search_person_output( + &store, + &output, + ( + (&context, principal), + (location_id, &target, run_id), + default_role, + ), + &query, + ) + .await? + .map(Json) + .ok_or_else(|| not_found("run not found")) +} + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/download", operation_id = "downloadPersonRunOutput", + params(("location_id" = Uuid, Path), ("target" = String, Path), ("run_id" = Uuid, Path), OutputDownloadQuery), + responses((status = 200, content_type = "text/plain", body = String, description = "The node's whole stream"), + (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody, description = "Needs view.evidence on every node the run selected"), + (status = 404, description = "Run not found for a person who may view the whole target"), + (status = 503, body = crate::api::models::ApiErrorBody, description = "The server keeps no run output")), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn run_output_download( + (State(store), Extension(context), Extension(facts)): ( + State, + Extension, + Extension, + ), + Extension(default_role): Extension, + (Path((location_id, target, run_id)), Query(query)): ( + Path<(Uuid, String, Uuid)>, + Query, + ), + Extension(AuthenticatedPerson(principal, _)): Extension, +) -> Result { + let output = facts.output.ok_or_else(no_output_store)?; + let text = download_person_output( + &store, + &output, + ( + (&context, principal), + (location_id, &target, run_id), + default_role, + ), + &query, + ) + .await? + .ok_or_else(|| not_found("run not found"))?; + let file = format!( + "attachment; filename=\"{run_id}-{}-{}.txt\"", + query + .node + .replace(|character: char| !character.is_ascii_alphanumeric(), "_"), + query.stream.map_or("output", OutputStream::as_str) + ); + let mut response = + axum::body::Body::from_stream(text.map(|chunk| chunk.map_err(std::io::Error::other))) + .into_response(); + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + response.headers_mut().insert( + header::CONTENT_DISPOSITION, + HeaderValue::from_str(&file).map_err(|_| not_found("run not found"))?, + ); + Ok(response) +} + #[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/jobs/{job_key}", operation_id = "readPersonJob", params(("location_id" = Uuid, Path), ("target" = String, Path), ("job_key" = String, Path)), responses((status = 200, body = JobDetailRecord), (status = 401, description = "Session rejected"), diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_republish.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_republish.rs new file mode 100644 index 0000000000..4b09f6b0c7 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_republish.rs @@ -0,0 +1,97 @@ +//! A person, or a script with their session, asks a location to publish again and reads back its sets. + +use axum::extract::{Path, Query, State}; +use axum::{Extension, Json}; +use uuid::Uuid; + +use crate::api::errors::ApiError; +use crate::api::models::RepublishWaitQuery; +use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole}; +use crate::platform::main::person_reads::read_person_discovered::read_person_discovered; +use crate::platform::main::work::read_republish::read_republish; +use crate::platform::main::work::request_republish::request_republish; +use crate::platform::models::{DiscoveredReadback, PersonWorkRequest, RepublishStatus}; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; + +#[utoipa::path(post, path = "/api/control/locations/{location_id}/targets/{target}/republish", + operation_id = "requestRepublish", + params(("location_id" = Uuid, Path), ("target" = String, Path), ("x-sqb-csrf" = String, Header), + ("wait" = Option, Query, description = "Seconds to wait for the new snapshot or the publish error, at most 60; 0 or absent returns at once")), + request_body = PersonWorkRequest, + responses((status = 200, body = RepublishStatus), (status = 400, body = crate::api::models::ApiErrorBody), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn request( + (State(store), Extension(context)): (State, Extension), + (Path((location_id, target)), Query(options)): ( + Path<(Uuid, String)>, + Query, + ), + Extension(AuthenticatedPerson(principal, _)): Extension, + Json(request): Json, +) -> Result, ApiError> { + request_republish( + &store, + (&context, Some(principal)), + (location_id, &target), + &request, + ) + .await?; + let status = read_republish( + &store, + (&context, Some(principal)), + (location_id, &target, request.request_id), + options.wait.unwrap_or_default(), + ) + .await? + .ok_or_else(|| ControlError::Invalid("the republish request disappeared".into()))?; + Ok(Json(status)) +} + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/republish/{request_id}", + operation_id = "readRepublish", + params(("location_id" = Uuid, Path), ("target" = String, Path), ("request_id" = Uuid, Path), + ("wait" = Option, Query, description = "Seconds to wait while the republish is pending, at most 60")), + responses((status = 200, body = Option), (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody)), security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn read( + (State(store), Extension(context)): (State, Extension), + (Path((location_id, target, request_id)), Query(options)): ( + Path<(Uuid, String, Uuid)>, + Query, + ), + Extension(AuthenticatedPerson(principal, _)): Extension, +) -> Result>, ApiError> { + Ok(Json( + read_republish( + &store, + (&context, Some(principal)), + (location_id, &target, request_id), + options.wait.unwrap_or_default(), + ) + .await?, + )) +} + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/discovered", + operation_id = "readDiscovered", + params(("location_id" = Uuid, Path), ("target" = String, Path)), + responses((status = 200, body = Option), (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody)), security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn discovered( + (State(store), Extension(context)): (State, Extension), + Extension(default_role): Extension, + Path((location_id, target)): Path<(Uuid, String)>, + Extension(AuthenticatedPerson(principal, _)): Extension, +) -> Result>, ApiError> { + Ok(Json( + read_person_discovered( + &store, + (&context, principal), + (location_id, &target), + default_role, + ) + .await?, + )) +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/router.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/router.rs index 73ead0ebc8..cad27c6319 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/router.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/router.rs @@ -95,6 +95,10 @@ pub(crate) fn router(store: &ControlStore, feed: ChangeFeed) -> Router, Extension), + Extension(identity): Extension, + Path(run_id): Path, + Json(batch): Json, +) -> Result, ApiError> { + let claim_id = require_worker(&identity, run_id)?; + let output = facts.output.ok_or_else(no_output_store)?; + Ok(Json( + publish_output_batch(&store, &output, (run_id, claim_id), batch).await?, + )) +} + +/// A server started without an output store refuses output, saying why. +pub(crate) fn no_output_store() -> ApiError { + ApiError { + status: StatusCode::SERVICE_UNAVAILABLE, + message: "this server keeps no run output store".into(), + decision_id: None, + } +} + #[utoipa::path(post, path = "/api/runs/{run_id}/recall", params(("run_id" = Uuid, Path)), request_body = RecallBatch, responses((status = 200, body = InsertOutcome), (status = 400, body = crate::api::models::ApiErrorBody), diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/service_accounts.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/service_accounts.rs new file mode 100644 index 0000000000..badcaa8af8 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/service_accounts.rs @@ -0,0 +1,139 @@ +//! Service account administration; each change authorizes inside its own write. + +use axum::extract::{Path, State}; +use axum::{Extension, Json}; +use uuid::Uuid; + +use crate::api::errors::ApiError; +use crate::authorization::main::service_accounts::{ + create_service_account::create_service_account, list_service_accounts::list_service_accounts, + revoke_service_key::revoke_service_key, rotate_service_key::rotate_service_key, + set_service_account_disabled::set_service_account_disabled, + set_service_account_role::set_service_account_role, +}; +use crate::credentials::models::{ + AuditContext, AuthenticatedPerson, IssuedServiceKey, NewServiceAccount, + ServiceAccountAuthority, ServiceAccountRole, ServiceAccountState, ServiceAccountSummary, + ServiceKeyRotation, +}; +use crate::store::models::ControlStore; + +type Caller = (Extension, Extension); + +fn authority( + (Extension(context), Extension(AuthenticatedPerson(principal, _))): Caller, +) -> (AuditContext, ServiceAccountAuthority) { + (context, ServiceAccountAuthority::Person(principal)) +} + +#[utoipa::path(get, path = "/api/admin/service-accounts", operation_id = "listServiceAccounts", + description = "Every service account by name with its working keys, never the keys themselves. Needs user.manage or role.assign.", + responses((status = 200, body = Vec), (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = []), ("serviceKey" = [])))] +pub(crate) async fn list( + State(store): State, + caller: Caller, +) -> Result>, ApiError> { + let (context, authority) = authority(caller); + Ok(Json( + list_service_accounts(&store, (&context, authority)).await?, + )) +} + +#[utoipa::path(post, path = "/api/admin/service-accounts", operation_id = "createServiceAccount", + description = "Adds a service account with a built-in role everywhere and returns its first key, only this once. Needs user.manage and role.assign.", + params(("x-sqb-csrf" = String, Header, description = "Session CSRF token")), request_body = NewServiceAccount, + responses((status = 200, body = IssuedServiceKey), (status = 400, body = crate::api::models::ApiErrorBody), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = []), ("serviceKey" = [])))] +pub(crate) async fn create( + State(store): State, + caller: Caller, + Json(request): Json, +) -> Result, ApiError> { + let (context, authority) = authority(caller); + Ok(Json( + create_service_account(&store, (&context, authority), (&request, None)).await?, + )) +} + +#[utoipa::path(post, path = "/api/admin/service-accounts/{principal_id}/keys", operation_id = "rotateServiceAccountKey", + description = "Issues a new key, returned only this once. The replaced key works on for overlap_minutes (at most 1440), else stops now; a key already in an overlap stops now. Needs user.manage.", + params(("principal_id" = Uuid, Path), ("x-sqb-csrf" = String, Header, description = "Session CSRF token")), + request_body = ServiceKeyRotation, + responses((status = 200, body = IssuedServiceKey), (status = 400, body = crate::api::models::ApiErrorBody), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = []), ("serviceKey" = [])))] +pub(crate) async fn rotate( + State(store): State, + Path(principal_id): Path, + caller: Caller, + Json(rotation): Json, +) -> Result, ApiError> { + let (context, authority) = authority(caller); + Ok(Json( + rotate_service_key(&store, (&context, authority), (principal_id, rotation)).await?, + )) +} + +#[utoipa::path(post, path = "/api/admin/service-accounts/{principal_id}/keys/{key_id}/revoke", operation_id = "revokeServiceAccountKey", + description = "Stops one working key now, such as an old key before its overlap ends. Needs user.manage.", + params(("principal_id" = Uuid, Path), ("key_id" = Uuid, Path), ("x-sqb-csrf" = String, Header, description = "Session CSRF token")), + responses((status = 200, body = ServiceAccountSummary), (status = 400, body = crate::api::models::ApiErrorBody), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = []), ("serviceKey" = [])))] +pub(crate) async fn revoke( + State(store): State, + Path((principal_id, key_id)): Path<(Uuid, Uuid)>, + caller: Caller, +) -> Result, ApiError> { + let (context, authority) = authority(caller); + Ok(Json( + revoke_service_key(&store, (&context, authority), (principal_id, key_id)).await?, + )) +} + +#[utoipa::path(post, path = "/api/admin/service-accounts/{principal_id}/disabled", operation_id = "setServiceAccountDisabled", + description = "Disabling refuses every key of the account at once; enabling accepts the same keys again. Needs user.manage.", + params(("principal_id" = Uuid, Path), ("x-sqb-csrf" = String, Header, description = "Session CSRF token")), + request_body = ServiceAccountState, + responses((status = 200, body = ServiceAccountSummary), (status = 400, body = crate::api::models::ApiErrorBody), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = []), ("serviceKey" = [])))] +pub(crate) async fn disable( + State(store): State, + Path(principal_id): Path, + caller: Caller, + Json(state): Json, +) -> Result, ApiError> { + let (context, authority) = authority(caller); + Ok(Json( + set_service_account_disabled( + &store, + (&context, authority), + (principal_id, state.disabled), + ) + .await?, + )) +} + +#[utoipa::path(post, path = "/api/admin/service-accounts/{principal_id}/role", operation_id = "setServiceAccountRole", + description = "Gives the account a built-in role everywhere in place of its other built-in roles everywhere. Needs role.assign.", + params(("principal_id" = Uuid, Path), ("x-sqb-csrf" = String, Header, description = "Session CSRF token")), + request_body = ServiceAccountRole, + responses((status = 200, body = ServiceAccountSummary), (status = 400, body = crate::api::models::ApiErrorBody), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = []), ("serviceKey" = [])))] +pub(crate) async fn role( + State(store): State, + Path(principal_id): Path, + caller: Caller, + Json(request): Json, +) -> Result, ApiError> { + let (context, authority) = authority(caller); + Ok(Json( + set_service_account_role(&store, (&context, authority), (principal_id, request.role)) + .await?, + )) +} diff --git a/crates/sqlbuild-orchestration/src/api/constants.rs b/crates/sqlbuild-orchestration/src/api/constants.rs index cd6dcafdf7..2ce51abd2e 100644 --- a/crates/sqlbuild-orchestration/src/api/constants.rs +++ b/crates/sqlbuild-orchestration/src/api/constants.rs @@ -61,6 +61,10 @@ pub(crate) const DOCKER_IMAGE_HEX_LENGTH: usize = 64; pub(crate) const HTTPS_SCHEME: &str = "https"; pub(crate) const HTTP_SCHEME: &str = "http"; pub(crate) const LOOPBACK_HOST: &str = "localhost"; +/// The port a browser leaves out of an HTTP authority. +pub(crate) const HTTP_PORT: u16 = 80; +/// The port a browser leaves out of an HTTPS authority. +pub(crate) const HTTPS_PORT: u16 = 443; pub(crate) const ROOT_PATH: &str = "/"; pub(crate) const UI_INDEX_PATH: &str = "/index.html"; pub(crate) const UI_IMMUTABLE_PREFIX: &str = "/_app/immutable/"; diff --git a/crates/sqlbuild-orchestration/src/api/main/openapi_document.rs b/crates/sqlbuild-orchestration/src/api/main/openapi_document.rs index 21bea0101a..c66be1d51b 100644 --- a/crates/sqlbuild-orchestration/src/api/main/openapi_document.rs +++ b/crates/sqlbuild-orchestration/src/api/main/openapi_document.rs @@ -16,6 +16,21 @@ pub fn openapi_document() -> utoipa::openapi::OpenApi { "bearer", SecurityScheme::Http(HttpBuilder::new().scheme(HttpAuthScheme::Bearer).build()), ); + document + .components + .get_or_insert_with(Default::default) + .add_security_scheme( + "serviceKey", + SecurityScheme::Http( + HttpBuilder::new() + .scheme(HttpAuthScheme::Bearer) + .description(Some( + "A service account key, sqbk_…, from sqb admin create-service-account or the \ + Service accounts tab. Accepted on any listen address.", + )) + .build(), + ), + ); document .components .get_or_insert_with(Default::default) diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index 1c85ebc109..b27a555096 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -1,5 +1,9 @@ //! Typed HTTP responses shared with the generated OpenAPI contract. +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + use serde::{Deserialize, Serialize}; use crate::api::_helpers::authentication::password_sessions; @@ -7,8 +11,8 @@ use crate::api::_helpers::authentication::{cli_login, oidc}; use crate::api::_helpers::resources::{ administrators, audit, changed_builds, changes, location_health, location_work, person_bootstrap, person_checks, person_location_work, person_maintenance, person_node_sql, - person_operations, person_plans, person_reads, person_selection, run_reads, runs, snapshots, - trigger_reads, warehouse_metadata, + person_operations, person_plans, person_reads, person_republish, person_selection, run_reads, + runs, service_accounts, snapshots, trigger_reads, warehouse_metadata, }; #[derive(Debug, utoipa::OpenApi)] @@ -19,6 +23,13 @@ use crate::api::_helpers::resources::{ administrators::holdings, administrators::definitions, administrators::server, + crate::api::_helpers::authentication::service_keys::keys_only_mode, + service_accounts::list, + service_accounts::create, + service_accounts::rotate, + service_accounts::revoke, + service_accounts::disable, + service_accounts::role, audit::read, person_operations::request_job, person_operations::request_adhoc, @@ -43,6 +54,10 @@ use crate::api::_helpers::resources::{ person_reads::node_costs, person_reads::run_statement_sql, person_reads::run_output, + person_reads::run_output_index, + person_reads::run_output_lines, + person_reads::run_output_search, + person_reads::run_output_download, person_reads::run_node_error, person_reads::jobs, person_reads::job, @@ -71,6 +86,9 @@ use crate::api::_helpers::resources::{ person_location_work::request, person_location_work::request_sync, person_location_work::result, + person_republish::request, + person_republish::read, + person_republish::discovered, person_plans::request, person_plans::read, person_plans::summary, @@ -103,6 +121,7 @@ use crate::api::_helpers::resources::{ runs::report, runs::heartbeat, runs::output, + runs::output_batch, runs::recall, run_reads::recent, run_reads::nodes, @@ -139,6 +158,13 @@ pub(crate) struct PlatformEventsQuery { pub(crate) limit: Option, } +/// How long a republish request or read waits for its result, in seconds. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RepublishWaitQuery { + pub(crate) wait: Option, +} + #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub(crate) struct ReadQuery { @@ -238,6 +264,14 @@ pub enum LoginMode { Oidc, /// `sqb dev` on loopback: no sign-in, every request acts as the local development person. Disabled, + /// No sign-in for people: only service account keys call the server. + Keys, +} + +/// How a server without a session is signed in to, answered before sign-in only where people can't. +#[derive(Clone, Copy, Debug, Serialize, utoipa::ToSchema)] +pub struct LoginModeAnswer { + pub login_mode: LoginMode, } /// What the UI needs first: how people sign in, and what this person may see and do. @@ -280,8 +314,19 @@ pub struct DevelopmentScope { pub location_id: uuid::Uuid, pub target: String, pub triggers: bool, - /// The local person every loopback request acts as. + /// The local person every accepted request acts as. pub principal_id: uuid::Uuid, + /// Names taken in `Host` and `Origin` besides the local ones, each `name` or `name:port`. + pub allowed_hosts: Vec, + /// An explicit opt-in to serve without sign-in beyond loopback. + pub listens_beyond_loopback: bool, +} + +/// What a development request's `Host` and `Origin` may say, in lower case. +#[derive(Clone, Debug)] +pub(crate) struct DevelopmentAuthorities { + pub(crate) hosts: Vec, + pub(crate) origins: Vec, } /// The one way people sign in to this server, if any. @@ -664,6 +709,8 @@ pub struct ServerFacts { pub attention_snooze: crate::acknowledgements::models::AttentionSnooze, /// The address people reach the server at, which sensor events link runs under; `None` without a sign-in origin. pub origin: Option, + /// Where run output is kept; `None` on a server that keeps none, which refuses output reads and batches. + pub output: Option, } /// The server's version, storage, sign-in and retention, for administrators. @@ -695,3 +742,7 @@ pub struct ServerRetention { pub location_health_days: i64, pub sensor_evaluation_days: i64, } + +/// When each service key's refusal was last audited, kept per router so the throttle stays local. +#[derive(Clone, Debug, Default)] +pub(crate) struct KeyRefusals(pub(crate) Arc>>); diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs index 5002a82e3a..b53bd6afe7 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrator_roles.rs @@ -92,14 +92,17 @@ pub(crate) async fn assign_role_in( ) .await; } - assign_scoped_role(transaction, context, request).await + let (transaction, applied) = write_scoped_role(transaction, context, request).await?; + commit(transaction).await?; + Ok(applied) } -async fn assign_scoped_role( +/// Writes and audits one assignment or revocation of a role that isn't admin, leaving the commit to the caller. +pub(crate) async fn write_scoped_role( transaction: ControlTransaction, context: &AuditContext, request: &RoleAssignmentRequest, -) -> Result { +) -> Result<(ControlTransaction, bool), ControlError> { let role = serde_json::to_value(&request.role) .map_err(|error| ControlError::Invalid(error.to_string()))?; let key = serde_json::to_string(&( @@ -139,6 +142,5 @@ async fn assign_scoped_role( .await?; transaction.changes.insert(Change::Credentials); } - commit(transaction).await?; - Ok(applied) + Ok((transaction, applied)) } diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs index e84dfc3789..c2a3e098c1 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/administrators.rs @@ -57,7 +57,7 @@ pub(crate) async fn grant_installation_admin( Ok((transaction, applied)) } -/// Another active installation administrator exists; a lost one is restored with grant-admin. +/// Another active installation administrator who is a person exists; a lost one is restored with grant-admin. pub(crate) async fn remaining_administrator( transaction: ControlTransaction, principal_id: Uuid, @@ -65,7 +65,8 @@ pub(crate) async fn remaining_administrator( let (transaction, rows) = query(transaction, "SELECT COUNT(*) AS administrators FROM sqb_role_assignments a JOIN sqb_principals p USING(principal_id) \ WHERE a.role_key='admin' AND a.location_id IS NULL AND a.target IS NULL \ - AND p.disabled_at IS NULL AND p.principal_id<>$1", + AND p.disabled_at IS NULL AND p.principal_id<>$1 \ + AND NOT EXISTS (SELECT 1 FROM sqb_service_accounts s WHERE s.principal_id=p.principal_id)", vec![Parameter::Id(principal_id)]).await?; Ok(( transaction, diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs index 6192d17a67..9bacc2272a 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/mod.rs @@ -7,3 +7,4 @@ pub(crate) mod person_grants; pub(crate) mod principal_names; pub(crate) mod proxy_people; pub(crate) mod role_overview; +pub(crate) mod service_accounts; diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/person_grants.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/person_grants.rs index 171b36d2db..23ec403fb7 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/person_grants.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/person_grants.rs @@ -12,7 +12,7 @@ use crate::store::main::query::query; use crate::store::models::{ControlTransaction, Parameter}; use crate::store::types::Row; -const ACTIONS: [Action; 18] = [ +const ACTIONS: [Action; 19] = [ Action::View, Action::ViewSql, Action::ViewEvidence, @@ -28,6 +28,7 @@ const ACTIONS: [Action; 18] = [ Action::SensorResetCursor, Action::RunAdhoc, Action::ConnectionTest, + Action::LocationRepublish, Action::UserManage, Action::RoleAssign, Action::AuditView, @@ -41,13 +42,17 @@ pub(crate) enum GrantDecision { fn role_allows(role: BuiltinRole, action: Action) -> bool { use Action::{ - ConnectionTest, JobRun, RunAdhoc, RunCancel, RunRerun, TriggerToggle, View, ViewSql, + ConnectionTest, JobRun, LocationRepublish, RunAdhoc, RunCancel, RunRerun, TriggerToggle, + View, ViewSql, }; match role { BuiltinRole::Admin => true, BuiltinRole::Viewer => action == View, BuiltinRole::Operator => { - matches!(action, View | JobRun | RunCancel | RunRerun | TriggerToggle) + matches!( + action, + View | JobRun | RunCancel | RunRerun | TriggerToggle | LocationRepublish + ) } BuiltinRole::Developer => matches!( action, @@ -58,6 +63,7 @@ fn role_allows(role: BuiltinRole, action: Action) -> bool { | ViewSql | RunAdhoc | ConnectionTest + | LocationRepublish ), } } diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/principal_names.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/principal_names.rs index 5e6605f309..ddd4f10adf 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/principal_names.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/principal_names.rs @@ -1,27 +1,40 @@ -//! Audit actors name principals by ID; people read them by name. +//! Audit actors name principals by ID; people read them by name and kind. use std::collections::BTreeMap; +use crate::credentials::models::PrincipalKind; use crate::store::errors::ControlError; use crate::store::main::query::query; use crate::store::models::ControlTransaction; -/// Each principal's name, keyed by its audit actor text, `principal:`. +/// Each principal's name and kind, keyed by its audit actor text, `principal:`. pub(crate) async fn principal_names( transaction: ControlTransaction, -) -> Result<(ControlTransaction, BTreeMap), ControlError> { +) -> Result< + ( + ControlTransaction, + BTreeMap, + ), + ControlError, +> { let (transaction, rows) = query( transaction, - "SELECT principal_id, name FROM sqb_principals", + "SELECT p.principal_id, p.name, CASE WHEN s.principal_id IS NULL THEN 0 ELSE 1 END AS service \ + FROM sqb_principals p LEFT JOIN sqb_service_accounts s ON s.principal_id=p.principal_id", Vec::new(), ) .await?; - let names: BTreeMap = rows + let names: BTreeMap = rows .iter() .filter_map(|row| { + let kind = if row["service"].as_i64() == Some(1) { + PrincipalKind::Service + } else { + PrincipalKind::Person + }; Some(( format!("principal:{}", row["principal_id"].as_str()?), - row["name"].as_str()?.to_owned(), + (row["name"].as_str()?.to_owned(), kind), )) }) .collect(); diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs index 438aea2976..9acd6e0c8f 100644 --- a/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/proxy_people.rs @@ -20,19 +20,22 @@ pub(crate) fn proxy_principal_id(username: &str) -> Uuid { ) } -/// Whether `principal_id` exists, and if so whether it is enabled. +/// Whether `principal_id` exists, and if so whether it is an enabled person; a service account never signs in. pub(crate) async fn principal_enabled( store: &ControlStore, principal_id: Uuid, ) -> Result, ControlError> { let (transaction, people) = query( begin(store, TransactionMode::Read).await?, - "SELECT disabled_at FROM sqb_principals WHERE principal_id=$1", + "SELECT p.disabled_at, s.principal_id AS service FROM sqb_principals p \ + LEFT JOIN sqb_service_accounts s ON s.principal_id=p.principal_id WHERE p.principal_id=$1", vec![Parameter::Id(principal_id)], ) .await?; commit(transaction).await?; - Ok(people.first().map(|person| person["disabled_at"].is_null())) + Ok(people + .first() + .map(|person| person["disabled_at"].is_null() && person["service"].is_null())) } /// Creates the person with the viewer role, or false when a principal's name matches in any case. diff --git a/crates/sqlbuild-orchestration/src/authorization/_helpers/service_accounts.rs b/crates/sqlbuild-orchestration/src/authorization/_helpers/service_accounts.rs new file mode 100644 index 0000000000..8b9ae3cac0 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/_helpers/service_accounts.rs @@ -0,0 +1,421 @@ +//! Service accounts: who may change them, how they are added, and how they read. + +use std::collections::BTreeMap; + +use chrono::{DateTime, Utc}; +use serde::Deserialize; +use serde_json::json; +use uuid::Uuid; + +use crate::authorization::_helpers::adder_scopes::{authorized, holds_all}; +use crate::authorization::_helpers::principal_names::principal_names; +use crate::credentials::main::audit::append_audit::append_audit; +use crate::credentials::main::identities::insert_principal::insert_principal; +use crate::credentials::models::{ + Action, AuditContext, BuiltinRole, PermissionScope, PrincipalKind, ServiceAccountAuthority, + ServiceAccountSummary, ServiceKeyOrigin, ServiceKeySummary, +}; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit, decode_row::decode_row, query::query}; +use crate::store::models::{Change, ControlStore, ControlTransaction, Parameter, TransactionMode}; +use crate::store::types::Row; + +/// The longest service account name; names are also audit actors and CLI arguments. +const MAX_NAME_CHARACTERS: usize = 63; + +/// Built-in roles from least to most, so an account holding several reports the highest. +const ROLE_ORDER: [BuiltinRole; 4] = [ + BuiltinRole::Viewer, + BuiltinRole::Operator, + BuiltinRole::Developer, + BuiltinRole::Admin, +]; + +type Names = BTreeMap; + +#[derive(Deserialize)] +struct PrincipalRow { + principal_id: Uuid, +} + +#[derive(Deserialize)] +struct RoleRow { + principal_id: Uuid, + role_key: serde_json::Value, +} + +#[derive(Deserialize)] +struct AccountRow { + principal_id: Uuid, + name: String, + description: Option, + created_at: DateTime, + created_by: String, + disabled_at: Option>, +} + +#[derive(Deserialize)] +struct HeldRole { + assignment_id: Uuid, + role_key: serde_json::Value, +} + +#[derive(Deserialize)] +struct KeyRow { + key_id: Uuid, + principal_id: Uuid, + prefix: String, + origin: ServiceKeyOrigin, + created_at: DateTime, + created_by: String, + last_used_at: Option>, + expires_at: Option>, + revoked_at: Option>, +} + +/// A write transaction for a change: authorized for every one of `scopes` for a person, or the owner's. +pub(crate) async fn begin_change( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), + scopes: &[PermissionScope], +) -> Result<(ControlTransaction, AuditContext), ControlError> { + match authority { + ServiceAccountAuthority::Owner => { + Ok((begin(store, TransactionMode::Write).await?, context.clone())) + } + ServiceAccountAuthority::Person(actor) => authorized(store, (context, actor), scopes).await, + } +} + +/// A transaction for reading service accounts: `user.manage`, else `role.assign`, whose refusal is audited. +pub(crate) async fn begin_listing( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), +) -> Result { + let ServiceAccountAuthority::Person(actor) = authority else { + return begin(store, TransactionMode::Read).await; + }; + let manage = PermissionScope::action(Action::UserManage, None); + let scope = if holds_all(store, actor, std::slice::from_ref(&manage)).await? { + manage + } else { + PermissionScope::action(Action::RoleAssign, None) + }; + Ok(authorized(store, (context, actor), &[scope]).await?.0) +} + +/// Lowercase letters, digits, `-` and `_`, starting with a letter, 2 to 63 characters. +pub(crate) fn check_name(name: &str) -> Result<(), ControlError> { + let valid = (2..=MAX_NAME_CHARACTERS).contains(&name.len()) + && name.starts_with(|first: char| first.is_ascii_lowercase()) + && name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_'); + if valid { + Ok(()) + } else { + Err(ControlError::Invalid(format!( + "a service account name is 2 to {MAX_NAME_CHARACTERS} lowercase letters, digits, - or _, \ + starting with a letter" + ))) + } +} + +/// Adds the principal `name` as a service account, refused when any principal has the name in any case. +pub(crate) async fn add_service_principal( + transaction: ControlTransaction, + context: &AuditContext, + (name, description): (&str, Option<&str>), +) -> Result<(ControlTransaction, Uuid), ControlError> { + let (transaction, taken) = query( + transaction, + "SELECT principal_id FROM sqb_principals WHERE lower(name)=$1", + vec![Parameter::Text(name.into())], + ) + .await?; + if !taken.is_empty() { + return Err(ControlError::Invalid(format!( + "{name} already names a person or service account" + ))); + } + let (transaction, principal_id) = + insert_principal(transaction, context, (Uuid::now_v7(), name)).await?; + let description = description + .map(str::trim) + .filter(|text| !text.is_empty()) + .map(str::to_owned); + let (transaction, _) = query( + transaction, + "INSERT INTO sqb_service_accounts (principal_id, description, created_by) VALUES ($1,$2,$3)", + vec![ + Parameter::Id(principal_id), + Parameter::OptionalText(description), + Parameter::Text(context.actor.clone()), + ], + ) + .await?; + Ok((transaction, principal_id)) +} + +/// The service account `principal_id`, refused as invalid when it is a person or doesn't exist. +pub(crate) async fn require_service_account( + transaction: ControlTransaction, + principal_id: Uuid, +) -> Result { + let (transaction, rows) = query( + transaction, + "SELECT principal_id FROM sqb_service_accounts WHERE principal_id=$1", + vec![Parameter::Id(principal_id)], + ) + .await?; + if rows.is_empty() { + return Err(ControlError::Invalid(format!( + "no service account {principal_id}" + ))); + } + Ok(transaction) +} + +/// A write changing `principal_id` that needs `user.manage`, refused when it isn't a service account. +pub(crate) async fn begin_account_change( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), + principal_id: Uuid, +) -> Result<(ControlTransaction, AuditContext), ControlError> { + let manage = PermissionScope::action(Action::UserManage, None); + let (transaction, authorized) = begin_change(store, (context, authority), &[manage]).await?; + Ok(( + require_service_account(transaction, principal_id).await?, + authorized, + )) +} + +/// Commits a change to `principal_id` and returns the account as it now reads. +pub(crate) async fn finish_change( + transaction: ControlTransaction, + principal_id: Uuid, +) -> Result { + let (transaction, account) = service_account_summary(transaction, principal_id).await?; + commit(transaction).await?; + Ok(account) +} + +/// The service account named `name`, for the CLI, which names accounts rather than numbering them. +pub(crate) async fn service_account_named( + store: &ControlStore, + name: &str, +) -> Result { + let (transaction, rows) = query( + begin(store, TransactionMode::Read).await?, + "SELECT p.principal_id FROM sqb_principals p JOIN sqb_service_accounts s ON s.principal_id=p.principal_id \ + WHERE p.name=$1", + vec![Parameter::Text(name.into())], + ) + .await?; + commit(transaction).await?; + let Some(row) = rows.into_iter().next() else { + return Err(ControlError::Invalid(format!( + "no service account named {name}" + ))); + }; + Ok(decode_row::(row)?.principal_id) +} + +/// Records a change to service account `principal_id` in the audit log, under the acting principal. +pub(crate) async fn audit_change( + transaction: ControlTransaction, + context: &AuditContext, + (principal_id, action): (Uuid, &str), + (before, after): (serde_json::Value, serde_json::Value), +) -> Result { + append_audit( + transaction, + context, + (Uuid::now_v7(), action), + (json!({"principal_id": principal_id}), before, after), + ) + .await +} + +/// The built-in role a stored `role_key` names; custom roles name none. +pub(crate) fn builtin_role(role_key: &serde_json::Value) -> Option { + ROLE_ORDER.into_iter().find(|role| json!(role) == *role_key) +} + +/// Each account's highest built-in role everywhere. +fn highest_roles(rows: Vec) -> Result, ControlError> { + let mut held: BTreeMap = BTreeMap::new(); + for row in rows { + let row: RoleRow = decode_row(row)?; + let Some(role) = builtin_role(&row.role_key) else { + continue; + }; + let rank = |role: &BuiltinRole| ROLE_ORDER.iter().position(|r| r == role); + if held + .get(&row.principal_id) + .is_none_or(|current| rank(&role) > rank(current)) + { + held.insert(row.principal_id, role); + } + } + Ok(held) +} + +/// Who made something, by name; none when the control-store owner did. +fn made_by(names: &Names, actor: &str) -> Option { + names.get(actor).map(|(name, _)| name.clone()) +} + +/// Whether a key works at `now`, or will once its account is enabled. +fn working(key: &KeyRow, now: DateTime) -> bool { + key.revoked_at.is_none() && key.expires_at.is_none_or(|end| end > now) +} + +fn key_summary(key: &KeyRow, names: &Names) -> ServiceKeySummary { + ServiceKeySummary { + key_id: key.key_id, + prefix: key.prefix.clone(), + origin: key.origin, + created_at: key.created_at, + created_by: made_by(names, &key.created_by), + last_used_at: key.last_used_at, + expires_at: key.expires_at, + } +} + +/// One account with its working keys, the current one first, and its newest use of any key. +fn account_summary( + account: AccountRow, + (keys, roles, names): (&[KeyRow], &BTreeMap, &Names), + now: DateTime, +) -> ServiceAccountSummary { + let mine: Vec<&KeyRow> = keys + .iter() + .filter(|key| key.principal_id == account.principal_id) + .collect(); + let mut working_keys: Vec = mine + .iter() + .filter(|key| working(key, now)) + .map(|key| key_summary(key, names)) + .collect(); + working_keys.sort_by_key(|key| key.expires_at.is_some()); + ServiceAccountSummary { + principal_id: account.principal_id, + role: roles.get(&account.principal_id).copied(), + created_by: made_by(names, &account.created_by), + name: account.name, + description: account.description, + created_at: account.created_at, + disabled_at: account.disabled_at, + last_used_at: mine.iter().filter_map(|key| key.last_used_at).max(), + keys: working_keys, + } +} + +/// Service accounts by name, or only `principal_id`, with the keys that work at `transaction.now`. +pub(crate) async fn service_account_summaries( + transaction: ControlTransaction, + principal_id: Option, +) -> Result<(ControlTransaction, Vec), ControlError> { + let now = transaction.now; + let (transaction, accounts) = query( + transaction, + "SELECT p.principal_id, p.name, p.created_at, p.disabled_at, s.description, s.created_by \ + FROM sqb_principals p JOIN sqb_service_accounts s ON s.principal_id=p.principal_id \ + WHERE $1 IS NULL OR p.principal_id=$1 ORDER BY p.name", + vec![Parameter::OptionalId(principal_id)], + ) + .await?; + let (transaction, keys) = query(transaction, + "SELECT k.key_id, k.principal_id, k.prefix, k.origin, k.created_at, k.created_by, k.last_used_at, \ + k.expires_at, k.revoked_at FROM sqb_service_account_keys k \ + WHERE $1 IS NULL OR k.principal_id=$1 ORDER BY k.created_at DESC, k.key_id DESC", + vec![Parameter::OptionalId(principal_id)]).await?; + let (transaction, roles) = query( + transaction, + "SELECT a.principal_id, a.role_key FROM sqb_role_assignments a JOIN sqb_service_accounts s \ + ON s.principal_id=a.principal_id WHERE a.location_id IS NULL AND a.target IS NULL", + Vec::new(), + ) + .await?; + let (transaction, names) = principal_names(transaction).await?; + let roles = highest_roles(roles)?; + let keys: Vec = keys + .into_iter() + .map(decode_row::) + .collect::>()?; + let accounts: Vec = accounts + .into_iter() + .map(decode_row::) + .collect::>()?; + let summaries: Vec = accounts + .into_iter() + .map(|account| account_summary(account, (&keys, &roles, &names), now)) + .collect(); + Ok((transaction, summaries)) +} + +/// The one summary of `principal_id`, read in `transaction` after a change. +pub(crate) async fn service_account_summary( + transaction: ControlTransaction, + principal_id: Uuid, +) -> Result<(ControlTransaction, ServiceAccountSummary), ControlError> { + let (transaction, mut summaries) = + service_account_summaries(transaction, Some(principal_id)).await?; + let summary = summaries + .pop() + .ok_or_else(|| ControlError::Invalid(format!("no service account {principal_id}")))?; + Ok((transaction, summary)) +} + +/// The summary of `principal_id`, read once a change has committed. +pub(crate) async fn read_service_account( + store: &ControlStore, + principal_id: Uuid, +) -> Result { + let (transaction, account) = + service_account_summary(begin(store, TransactionMode::Read).await?, principal_id).await?; + commit(transaction).await?; + Ok(account) +} + +/// Removes and audits every built-in role everywhere of `principal_id` other than `role`. +pub(crate) async fn revoke_other_roles( + transaction: ControlTransaction, + context: &AuditContext, + (principal_id, role): (Uuid, BuiltinRole), +) -> Result { + let (mut transaction, rows) = query( + transaction, + "SELECT assignment_id, role_key FROM sqb_role_assignments \ + WHERE principal_id=$1 AND location_id IS NULL AND target IS NULL", + vec![Parameter::Id(principal_id)], + ) + .await?; + for row in rows { + let held_row: HeldRole = decode_row(row)?; + let Some(held) = builtin_role(&held_row.role_key).filter(|held| *held != role) else { + continue; + }; + let removed; + (transaction, removed) = query( + transaction, + "DELETE FROM sqb_role_assignments WHERE assignment_id=$1 RETURNING assignment_id", + vec![Parameter::Id(held_row.assignment_id)], + ) + .await?; + transaction = append_audit( + transaction, + context, + (Uuid::now_v7(), "role.revoked"), + ( + json!({"principal_id": principal_id, "role": held, "location_id": null, "target": null}), + json!(null), + json!({"assignments": removed}), + ), + ) + .await?; + transaction.changes.insert(Change::Credentials); + } + Ok(transaction) +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs b/crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs index 9cc9aeec5a..cae14eb722 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/decisions/read_security_audit.rs @@ -28,7 +28,10 @@ pub async fn read_security_audit( let (transaction, names) = principal_names(transaction).await?; commit(transaction).await?; for event in &mut events { - event.actor_name = names.get(&event.actor).cloned(); + if let Some((name, kind)) = names.get(&event.actor) { + event.actor_name = Some(name.clone()); + event.actor_kind = Some(*kind); + } } Ok(events) } diff --git a/crates/sqlbuild-orchestration/src/authorization/main/mod.rs b/crates/sqlbuild-orchestration/src/authorization/main/mod.rs index 155e9bd2a1..584ef91c1e 100644 --- a/crates/sqlbuild-orchestration/src/authorization/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/authorization/main/mod.rs @@ -1,3 +1,4 @@ pub mod decisions; pub mod people; pub mod roles; +pub mod service_accounts; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/create_service_account.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/create_service_account.rs new file mode 100644 index 0000000000..fbbca25c56 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/create_service_account.rs @@ -0,0 +1,64 @@ +//! A service account is a principal with one built-in role and a key that is returned only once. + +use serde_json::json; + +use crate::authorization::_helpers::adder_scopes::required_scopes; +use crate::authorization::_helpers::administrator_roles::assign_role_in; +use crate::authorization::_helpers::service_accounts::{ + add_service_principal, audit_change, begin_change, check_name, read_service_account, +}; +use crate::credentials::main::service_keys::issue_service_key::issue_service_key; +use crate::credentials::models::{ + AuditContext, IssuedServiceKey, NewServiceAccount, RoleAssignmentRequest, RoleKey, + ServiceAccountAuthority, +}; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; + +/// Adds `request`'s account with a new key or the owner's `chosen_key`; a person needs `user.manage` and `role.assign`. +pub async fn create_service_account( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), + (request, chosen_key): (&NewServiceAccount, Option<&str>), +) -> Result { + let name = request.name.trim(); + check_name(name)?; + if chosen_key.is_some() && matches!(authority, ServiceAccountAuthority::Person(_)) { + return Err(ControlError::Invalid( + "a chosen key can only be imported with the CLI".into(), + )); + } + let scopes = required_scopes(Some(request.role)); + let (transaction, authorized) = begin_change(store, (context, authority), &scopes).await?; + let (transaction, principal_id) = add_service_principal( + transaction, + &authorized, + (name, request.description.as_deref()), + ) + .await?; + let (transaction, issued) = + issue_service_key(transaction, &authorized, (principal_id, chosen_key)).await?; + let transaction = audit_change( + transaction, + &authorized, + (principal_id, "service_account.created"), + ( + json!(null), + json!({"name": name, "role": request.role, "key_prefix": issued.prefix, + "key_origin": issued.origin}), + ), + ) + .await?; + let role = RoleAssignmentRequest { + principal_id, + role: RoleKey::Builtin(request.role), + location_id: None, + target: None, + revoke: false, + }; + assign_role_in(transaction, &authorized, &role).await?; + Ok(IssuedServiceKey { + account: read_service_account(store, principal_id).await?, + key: issued.key, + }) +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/find_service_account.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/find_service_account.rs new file mode 100644 index 0000000000..612940b0ff --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/find_service_account.rs @@ -0,0 +1,12 @@ +//! The CLI names service accounts; the server's routes number them. + +use uuid::Uuid; + +use crate::authorization::_helpers::service_accounts::service_account_named; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; + +/// The principal of the service account named `name`. +pub async fn find_service_account(store: &ControlStore, name: &str) -> Result { + service_account_named(store, name).await +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/list_service_accounts.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/list_service_accounts.rs new file mode 100644 index 0000000000..4105585fa0 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/list_service_accounts.rs @@ -0,0 +1,18 @@ +//! Administrators who manage people or give roles see every service account and its working keys. + +use crate::authorization::_helpers::service_accounts::{begin_listing, service_account_summaries}; +use crate::credentials::models::{AuditContext, ServiceAccountAuthority, ServiceAccountSummary}; +use crate::store::errors::ControlError; +use crate::store::main::commit::commit; +use crate::store::models::ControlStore; + +/// Every service account by name; a person needs `user.manage` or `role.assign` everywhere. +pub async fn list_service_accounts( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), +) -> Result, ControlError> { + let transaction = begin_listing(store, (context, authority)).await?; + let (transaction, accounts) = service_account_summaries(transaction, None).await?; + commit(transaction).await?; + Ok(accounts) +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/mod.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/mod.rs new file mode 100644 index 0000000000..4c54be5dec --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/mod.rs @@ -0,0 +1,7 @@ +pub mod create_service_account; +pub mod find_service_account; +pub mod list_service_accounts; +pub mod revoke_service_key; +pub mod rotate_service_key; +pub mod set_service_account_disabled; +pub mod set_service_account_role; diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/revoke_service_key.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/revoke_service_key.rs new file mode 100644 index 0000000000..ace8226603 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/revoke_service_key.rs @@ -0,0 +1,52 @@ +//! Any working key can be stopped at once, such as an old key before its overlap ends. + +use serde_json::json; +use uuid::Uuid; + +use crate::authorization::_helpers::service_accounts::{ + audit_change, begin_account_change, finish_change, +}; +use crate::credentials::models::{AuditContext, ServiceAccountAuthority, ServiceAccountSummary}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{Change, ControlStore, Parameter}; + +/// Stops `key_id` of `principal_id` now; a person needs `user.manage` everywhere. +pub async fn revoke_service_key( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), + (principal_id, key_id): (Uuid, Uuid), +) -> Result { + let (transaction, authorized) = + begin_account_change(store, (context, authority), principal_id).await?; + let now = transaction.now; + let (mut transaction, stopped) = query( + transaction, + "UPDATE sqb_service_account_keys SET revoked_at=$1 WHERE key_id=$2 AND principal_id=$3 \ + AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at>$1) RETURNING prefix", + vec![ + Parameter::Time(now), + Parameter::Id(key_id), + Parameter::Id(principal_id), + ], + ) + .await?; + let Some(prefix) = stopped.first().and_then(|row| row["prefix"].as_str()) else { + return Err(ControlError::Invalid(format!( + "service account {principal_id} has no working key {key_id}" + ))); + }; + let prefix = prefix.to_owned(); + transaction.changes.insert(Change::Credentials); + let transaction = audit_change( + transaction, + &authorized, + (principal_id, "service_account.key_revoked"), + ( + json!({"key_id": key_id, "key_prefix": prefix, "revoked": false}), + json!({"key_id": key_id, "key_prefix": prefix, "revoked": true}), + ), + ) + .await?; + finish_change(transaction, principal_id).await +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/rotate_service_key.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/rotate_service_key.rs new file mode 100644 index 0000000000..1f82bf03af --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/rotate_service_key.rs @@ -0,0 +1,73 @@ +//! Rotation issues a new key; the replaced key works on for the overlap, and at most one old key is kept. + +use chrono::Duration; +use serde_json::json; +use uuid::Uuid; + +use crate::authorization::_helpers::service_accounts::{ + audit_change, begin_account_change, finish_change, +}; +use crate::credentials::constants::MAX_KEY_OVERLAP_MINUTES; +use crate::credentials::main::service_keys::issue_service_key::issue_service_key; +use crate::credentials::models::{ + AuditContext, IssuedServiceKey, ServiceAccountAuthority, ServiceKeyRotation, +}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{ControlStore, Parameter}; +use crate::store::types::Row; + +/// Issues `principal_id` a new key, keeping the replaced one for the overlap; a person needs `user.manage`. +pub async fn rotate_service_key( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), + (principal_id, rotation): (Uuid, ServiceKeyRotation), +) -> Result { + let overlap = rotation.overlap_minutes.unwrap_or(0); + if !(0..=MAX_KEY_OVERLAP_MINUTES).contains(&overlap) { + return Err(ControlError::Invalid(format!( + "the overlap is 0 to {MAX_KEY_OVERLAP_MINUTES} minutes" + ))); + } + let (transaction, authorized) = + begin_account_change(store, (context, authority), principal_id).await?; + let now = transaction.now; + let (transaction, replaced) = query(transaction, + "UPDATE sqb_service_account_keys SET revoked_at=$1 WHERE principal_id=$2 AND revoked_at IS NULL \ + AND expires_at IS NOT NULL AND expires_at>$1 RETURNING prefix", + vec![Parameter::Time(now), Parameter::Id(principal_id)]).await?; + let ends = (overlap > 0).then(|| now + Duration::minutes(overlap)); + let (transaction, current) = match ends { + Some(ends) => query(transaction, + "UPDATE sqb_service_account_keys SET expires_at=$1 WHERE principal_id=$2 AND revoked_at IS NULL \ + AND expires_at IS NULL RETURNING prefix", + vec![Parameter::Time(ends), Parameter::Id(principal_id)]).await?, + None => query(transaction, + "UPDATE sqb_service_account_keys SET revoked_at=$1 WHERE principal_id=$2 AND revoked_at IS NULL \ + AND expires_at IS NULL RETURNING prefix", + vec![Parameter::Time(now), Parameter::Id(principal_id)]).await?, + }; + let (transaction, issued) = + issue_service_key(transaction, &authorized, (principal_id, None)).await?; + let transaction = audit_change( + transaction, + &authorized, + (principal_id, "service_account.key_rotated"), + ( + json!({"key_prefixes": prefixes(¤t), "stopped_old_key_prefixes": prefixes(&replaced)}), + json!({"key_prefix": issued.prefix, "old_key_expires_at": ends}), + ), + ) + .await?; + Ok(IssuedServiceKey { + account: finish_change(transaction, principal_id).await?, + key: issued.key, + }) +} + +/// The prefixes of the keys an update returned. +fn prefixes(rows: &[Row]) -> Vec { + rows.iter() + .filter_map(|row| row["prefix"].as_str().map(str::to_owned)) + .collect() +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/set_service_account_disabled.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/set_service_account_disabled.rs new file mode 100644 index 0000000000..cd7f67d10d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/set_service_account_disabled.rs @@ -0,0 +1,53 @@ +//! Disabling refuses every key of a service account at once; enabling accepts the same keys again. + +use serde_json::json; +use uuid::Uuid; + +use crate::authorization::_helpers::service_accounts::{ + audit_change, begin_account_change, finish_change, +}; +use crate::credentials::models::{AuditContext, ServiceAccountAuthority, ServiceAccountSummary}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{Change, ControlStore, Parameter}; + +/// Disables or enables `principal_id`; a person needs `user.manage` everywhere. Repeating it changes nothing. +pub async fn set_service_account_disabled( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), + (principal_id, disabled): (Uuid, bool), +) -> Result { + let (transaction, authorized) = + begin_account_change(store, (context, authority), principal_id).await?; + let now = transaction.now; + let (mut transaction, changed) = if disabled { + query(transaction, + "UPDATE sqb_principals SET disabled_at=$1 WHERE principal_id=$2 AND disabled_at IS NULL RETURNING principal_id", + vec![Parameter::Time(now), Parameter::Id(principal_id)]).await? + } else { + query(transaction, + "UPDATE sqb_principals SET disabled_at=NULL WHERE principal_id=$1 AND disabled_at IS NOT NULL RETURNING principal_id", + vec![Parameter::Id(principal_id)]).await? + }; + if !changed.is_empty() { + transaction.changes.insert(Change::Credentials); + transaction = audit_change( + transaction, + &authorized, + ( + principal_id, + if disabled { + "service_account.disabled" + } else { + "service_account.enabled" + }, + ), + ( + json!({"disabled": !disabled}), + json!({"disabled": disabled}), + ), + ) + .await?; + } + finish_change(transaction, principal_id).await +} diff --git a/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/set_service_account_role.rs b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/set_service_account_role.rs new file mode 100644 index 0000000000..cec933ea59 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/authorization/main/service_accounts/set_service_account_role.rs @@ -0,0 +1,56 @@ +//! A service account holds one built-in role everywhere: the new role and the old ones' removal commit together. + +use uuid::Uuid; + +use crate::authorization::_helpers::administrator_roles::write_scoped_role; +use crate::authorization::_helpers::administrators::grant_installation_admin; +use crate::authorization::_helpers::service_accounts::{ + begin_change, finish_change, require_service_account, revoke_other_roles, +}; +use crate::credentials::models::{ + Action, AuditContext, BuiltinRole, PermissionScope, RoleAssignmentRequest, RoleKey, + ServiceAccountAuthority, ServiceAccountSummary, +}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{ControlStore, Parameter}; + +/// Gives `principal_id` `role` everywhere in place of its other built-in roles; a person needs `role.assign`. +pub async fn set_service_account_role( + store: &ControlStore, + (context, authority): (&AuditContext, ServiceAccountAuthority), + (principal_id, role): (Uuid, BuiltinRole), +) -> Result { + let (transaction, authorized) = begin_change( + store, + (context, authority), + &[PermissionScope::action(Action::RoleAssign, None)], + ) + .await?; + let transaction = require_service_account(transaction, principal_id).await?; + let (transaction, enabled) = query( + transaction, + "SELECT principal_id FROM sqb_principals WHERE principal_id=$1 AND disabled_at IS NULL", + vec![Parameter::Id(principal_id)], + ) + .await?; + if enabled.is_empty() { + return Err(ControlError::Invalid( + "enable the service account before changing its role".into(), + )); + } + let transaction = revoke_other_roles(transaction, &authorized, (principal_id, role)).await?; + let (transaction, _) = if role == BuiltinRole::Admin { + grant_installation_admin(transaction, &authorized, principal_id, "manual").await? + } else { + let request = RoleAssignmentRequest { + principal_id, + role: RoleKey::Builtin(role), + location_id: None, + target: None, + revoke: false, + }; + write_scoped_role(transaction, &authorized, &request).await? + }; + finish_change(transaction, principal_id).await +} diff --git a/crates/sqlbuild-orchestration/src/credentials/_helpers/browser_sessions.rs b/crates/sqlbuild-orchestration/src/credentials/_helpers/browser_sessions.rs index 7e4a823aee..fbfaff828b 100644 --- a/crates/sqlbuild-orchestration/src/credentials/_helpers/browser_sessions.rs +++ b/crates/sqlbuild-orchestration/src/credentials/_helpers/browser_sessions.rs @@ -23,7 +23,8 @@ pub(crate) async fn issue_live_session( let (transaction, rows) = query(transaction, "SELECT p.principal_id FROM sqb_principals p LEFT JOIN sqb_password_credentials c \ ON c.principal_id=p.principal_id AND c.credential_id=$2 \ - WHERE p.principal_id=$1 AND p.disabled_at IS NULL AND ($2 IS NULL OR c.credential_id IS NOT NULL)", + WHERE p.principal_id=$1 AND p.disabled_at IS NULL AND ($2 IS NULL OR c.credential_id IS NOT NULL) \ + AND NOT EXISTS (SELECT 1 FROM sqb_service_accounts s WHERE s.principal_id=p.principal_id)", vec![Parameter::Id(principal_id), Parameter::OptionalId(credential_id)]).await?; if rows.is_empty() { return Ok((transaction, None)); @@ -43,6 +44,17 @@ pub(crate) async fn issue_session( context: &AuditContext, (principal_id, credential_id): (Uuid, Option), ) -> Result<(ControlTransaction, IssuedSession), ControlError> { + let (transaction, service) = query( + transaction, + "SELECT principal_id FROM sqb_service_accounts WHERE principal_id=$1", + vec![Parameter::Id(principal_id)], + ) + .await?; + if !service.is_empty() { + return Err(ControlError::Invalid( + "a service account has no sessions; it calls with its key".into(), + )); + } let now = transaction.now; let session_id = Uuid::now_v7(); let bearer = new_bearer(session_id)?; diff --git a/crates/sqlbuild-orchestration/src/credentials/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/credentials/_helpers/mod.rs index 020e67bc15..795a6961ec 100644 --- a/crates/sqlbuild-orchestration/src/credentials/_helpers/mod.rs +++ b/crates/sqlbuild-orchestration/src/credentials/_helpers/mod.rs @@ -6,4 +6,5 @@ pub(crate) mod password_sessions; pub(crate) mod passwords; pub(crate) mod scopes; pub(crate) mod secrets; +pub(crate) mod service_keys; pub(crate) mod tokens; diff --git a/crates/sqlbuild-orchestration/src/credentials/_helpers/service_keys.rs b/crates/sqlbuild-orchestration/src/credentials/_helpers/service_keys.rs new file mode 100644 index 0000000000..e21e4335ab --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/_helpers/service_keys.rs @@ -0,0 +1,67 @@ +//! Service account keys: made from 256 random bits, recognised by their prefix, stored only as a hash. + +use sqlbuild_recall::records::main::sha256_hex::sha256_hex; + +use crate::credentials::constants::{ + MAX_SERVICE_KEY_BYTES, MIN_IMPORTED_KEY_CHARACTERS, SERVICE_KEY_CHARACTERS, SERVICE_KEY_PREFIX, + SERVICE_KEY_SHOWN_CHARACTERS, +}; +use crate::store::errors::ControlError; + +const KEY_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; +/// The largest multiple of the alphabet's size in a byte; higher bytes are drawn again, so no character is likelier. +const UNBIASED_BYTES: u8 = 248; + +/// A new key: the prefix and letters and digits drawn uniformly from the operating system's random source. +pub(crate) fn new_service_key() -> Result { + let mut key = String::from(SERVICE_KEY_PREFIX); + let mut random = [0_u8; 64]; + while key.len() < SERVICE_KEY_PREFIX.len() + SERVICE_KEY_CHARACTERS { + getrandom::fill(&mut random) + .map_err(|_| ControlError::Invalid("could not generate a secure key".into()))?; + for byte in random.iter().filter(|byte| **byte < UNBIASED_BYTES) { + if key.len() == SERVICE_KEY_PREFIX.len() + SERVICE_KEY_CHARACTERS { + break; + } + key.push(char::from( + KEY_ALPHABET[usize::from(*byte) % KEY_ALPHABET.len()], + )); + } + } + Ok(key) +} + +/// A key an operator chose: the prefix, then at least the minimum of printable, non-space ASCII. +pub(crate) fn check_imported_key(key: &str) -> Result<(), ControlError> { + let Some(secret) = key.strip_prefix(SERVICE_KEY_PREFIX) else { + return Err(ControlError::Invalid(format!( + "an imported key must start with {SERVICE_KEY_PREFIX}" + ))); + }; + if secret.len() < MIN_IMPORTED_KEY_CHARACTERS { + return Err(ControlError::Invalid(format!( + "an imported key needs at least {MIN_IMPORTED_KEY_CHARACTERS} characters after \ + {SERVICE_KEY_PREFIX}; it has {}", + secret.chars().count() + ))); + } + if key.len() > MAX_SERVICE_KEY_BYTES || !secret.bytes().all(|byte| byte.is_ascii_graphic()) { + return Err(ControlError::Invalid(format!( + "an imported key is printable ASCII without spaces, at most {MAX_SERVICE_KEY_BYTES} \ + characters" + ))); + } + Ok(()) +} + +/// The non-secret start of a key that identifies it in lists and the audit log. +pub(crate) fn key_prefix(key: &str) -> String { + key.chars() + .take(SERVICE_KEY_PREFIX.len() + SERVICE_KEY_SHOWN_CHARACTERS) + .collect() +} + +/// What the store keeps of a key: its SHA-256, enough to recognise it and useless for using it. +pub(crate) fn key_hash(key: &str) -> String { + sha256_hex(key.as_bytes()) +} diff --git a/crates/sqlbuild-orchestration/src/credentials/constants.rs b/crates/sqlbuild-orchestration/src/credentials/constants.rs index a47221ed7d..a6fff092a5 100644 --- a/crates/sqlbuild-orchestration/src/credentials/constants.rs +++ b/crates/sqlbuild-orchestration/src/credentials/constants.rs @@ -18,3 +18,19 @@ pub(crate) const DUMMY_PASSWORD_HASH: &str = "$argon2id$v=19$m=19456,t=2,p=1$AAA pub(crate) const DEFAULT_AUDIT_RETENTION_DAYS: u16 = 400; pub(crate) const AUDIT_RETENTION_BATCH: usize = 100; + +/// Service account keys start with this, so people and secret scanners recognise them. +pub(crate) const SERVICE_KEY_PREFIX: &str = "sqbk_"; +/// Random letters and digits after the prefix in a key SQLBuild creates: about 238 bits. +pub(crate) const SERVICE_KEY_CHARACTERS: usize = 40; +/// The fewest characters after the prefix that a key chosen with `--key-from-env` may have. +pub(crate) const MIN_IMPORTED_KEY_CHARACTERS: usize = 32; +pub(crate) const MAX_SERVICE_KEY_BYTES: usize = 256; +/// Characters after the prefix shown to identify a key; the rest stays secret. +pub(crate) const SERVICE_KEY_SHOWN_CHARACTERS: usize = 6; +/// The longest a key replaced by a rotation keeps working. +pub(crate) const MAX_KEY_OVERLAP_MINUTES: i64 = 1440; +/// A key's last use is written at most this often, so busy callers don't write on every request. +pub(crate) const KEY_USE_INTERVAL_SECONDS: i64 = 60; +/// A refused key's audit entry is written at most this often per key, so a misconfigured script can't flood the log. +pub(crate) const KEY_REFUSAL_INTERVAL_SECONDS: u64 = 60; diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs index b752f8e567..5f838a4a67 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/list_people.rs @@ -1,4 +1,4 @@ -//! Administrators who manage people list every principal with sign-in facts, never secrets. +//! Administrators who manage people list every person with sign-in facts, never secrets; service accounts list apart. use std::collections::BTreeMap; @@ -34,7 +34,8 @@ pub async fn list_people( (SELECT COUNT(*) FROM sqb_sessions s WHERE s.principal_id=p.principal_id \ AND s.revoked_at IS NULL AND s.expires_at>$1 AND p.disabled_at IS NULL) AS active_sessions, \ (SELECT MAX(s.created_at) FROM sqb_sessions s WHERE s.principal_id=p.principal_id) AS last_signed_in_at \ - FROM sqb_principals p LEFT JOIN sqb_password_credentials c ON c.principal_id=p.principal_id ORDER BY p.name", + FROM sqb_principals p LEFT JOIN sqb_password_credentials c ON c.principal_id=p.principal_id \ + WHERE NOT EXISTS (SELECT 1 FROM sqb_service_accounts s WHERE s.principal_id=p.principal_id) ORDER BY p.name", vec![Parameter::Time(now)]).await?; let (transaction, memberships) = query( transaction, diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs index 126f3c51d3..786f86ede3 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/mod.rs @@ -2,3 +2,4 @@ pub mod create_principal; pub mod development_person; pub(crate) mod insert_principal; pub mod list_people; +pub mod recorded_name; diff --git a/crates/sqlbuild-orchestration/src/credentials/main/identities/recorded_name.rs b/crates/sqlbuild-orchestration/src/credentials/main/identities/recorded_name.rs new file mode 100644 index 0000000000..c0ae165ffa --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/main/identities/recorded_name.rs @@ -0,0 +1,21 @@ +//! The operator's CLI takes IDs and says what they name. + +use uuid::Uuid; + +use crate::store::errors::ControlError; +use crate::store::main::read_records::read_records; +use crate::store::models::{ControlStore, Parameter}; + +/// The name of the location or principal `id` identifies, or `None` when neither does. +pub async fn recorded_name(store: &ControlStore, id: Uuid) -> Result, ControlError> { + let named: Vec = read_records( + store, + "SELECT name FROM sqb_locations WHERE location_id=$1 \ + UNION ALL SELECT name FROM sqb_principals WHERE principal_id=$1", + vec![Parameter::Id(id)], + ) + .await?; + Ok(named + .into_iter() + .find_map(|row| row["name"].as_str().map(str::to_owned))) +} diff --git a/crates/sqlbuild-orchestration/src/credentials/main/mod.rs b/crates/sqlbuild-orchestration/src/credentials/main/mod.rs index 06dec347c3..cbbdd66307 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/mod.rs @@ -2,5 +2,6 @@ pub mod audit; pub(crate) mod cli_login; pub mod identities; pub mod locations; +pub(crate) mod service_keys; pub mod sessions; pub mod tokens; diff --git a/crates/sqlbuild-orchestration/src/credentials/main/service_keys/authenticate_service_key.rs b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/authenticate_service_key.rs new file mode 100644 index 0000000000..b7bef88902 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/authenticate_service_key.rs @@ -0,0 +1,48 @@ +//! A presented key is found by its hash; it works while unstopped, unexpired and its account enabled. + +use chrono::{DateTime, Utc}; + +use crate::credentials::_helpers::service_keys::key_hash; +use crate::credentials::models::{ServiceKeyCheck, ServiceKeyIdentity, ServiceKeyState}; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit, decode_row::decode_row, query::query}; +use crate::store::models::{ControlStore, Parameter, TransactionMode}; + +/// What `key` is at `now`: a working key, a known key refused and why, or no key the store knows. +pub(crate) async fn authenticate_service_key( + store: &ControlStore, + key: &str, + now: DateTime, +) -> Result { + let (transaction, rows) = query( + begin(store, TransactionMode::Read).await?, + "SELECT k.key_id, k.principal_id, k.expires_at, k.revoked_at, k.last_used_at, p.disabled_at \ + FROM sqb_service_account_keys k JOIN sqb_principals p ON p.principal_id=k.principal_id \ + JOIN sqb_service_accounts s ON s.principal_id=k.principal_id WHERE k.secret_hash=$1", + vec![Parameter::Text(key_hash(key))], + ) + .await?; + commit(transaction).await?; + let Some(row) = rows.into_iter().next() else { + return Ok(ServiceKeyCheck::Unknown); + }; + let state: ServiceKeyState = decode_row(row)?; + let refused = |reason| ServiceKeyCheck::Refused { + principal_id: state.principal_id, + key_id: state.key_id, + reason, + }; + Ok(if state.disabled_at.is_some() { + refused("the service account is disabled") + } else if state.revoked_at.is_some() { + refused("the key was stopped") + } else if state.expires_at.is_some_and(|end| end <= now) { + refused("the key's rotation overlap ended") + } else { + ServiceKeyCheck::Accepted(ServiceKeyIdentity { + principal_id: state.principal_id, + key_id: state.key_id, + last_used_at: state.last_used_at, + }) + }) +} diff --git a/crates/sqlbuild-orchestration/src/credentials/main/service_keys/issue_service_key.rs b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/issue_service_key.rs new file mode 100644 index 0000000000..97b0594bca --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/issue_service_key.rs @@ -0,0 +1,64 @@ +//! A service account's key is made here, or imported by the owner, and stored only as its hash. + +use uuid::Uuid; + +use crate::credentials::_helpers::service_keys::{ + check_imported_key, key_hash, key_prefix, new_service_key, +}; +use crate::credentials::models::{AuditContext, NewServiceKey, ServiceKeyOrigin}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{Change, ControlTransaction, Parameter}; + +/// Stores a new key for `principal_id`, or `chosen` once it passes the import rules, and returns it. +pub(crate) async fn issue_service_key( + transaction: ControlTransaction, + context: &AuditContext, + (principal_id, chosen): (Uuid, Option<&str>), +) -> Result<(ControlTransaction, NewServiceKey), ControlError> { + let (key, origin) = match chosen { + Some(key) => { + check_imported_key(key)?; + (key.to_owned(), ServiceKeyOrigin::Imported) + } + None => (new_service_key()?, ServiceKeyOrigin::Issued), + }; + let hash = key_hash(&key); + let (transaction, taken) = query( + transaction, + "SELECT key_id FROM sqb_service_account_keys WHERE secret_hash=$1", + vec![Parameter::Text(hash.clone())], + ) + .await?; + if !taken.is_empty() { + return Err(ControlError::Invalid( + "that key is already in use; choose another".into(), + )); + } + let prefix = key_prefix(&key); + let now = transaction.now; + let (mut transaction, _) = query( + transaction, + "INSERT INTO sqb_service_account_keys (key_id, principal_id, secret_hash, prefix, origin, created_at, created_by) \ + VALUES ($1,$2,$3,$4,$5,$6,$7)", + vec![ + Parameter::Id(Uuid::now_v7()), + Parameter::Id(principal_id), + Parameter::Text(hash), + Parameter::Text(prefix.clone()), + Parameter::Text(origin.as_str().into()), + Parameter::Time(now), + Parameter::Text(context.actor.clone()), + ], + ) + .await?; + transaction.changes.insert(Change::Credentials); + Ok(( + transaction, + NewServiceKey { + key, + prefix, + origin, + }, + )) +} diff --git a/crates/sqlbuild-orchestration/src/credentials/main/service_keys/mod.rs b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/mod.rs new file mode 100644 index 0000000000..148602cdd7 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/mod.rs @@ -0,0 +1,4 @@ +pub(crate) mod authenticate_service_key; +pub(crate) mod issue_service_key; +pub(crate) mod record_refused_key; +pub(crate) mod record_service_key_use; diff --git a/crates/sqlbuild-orchestration/src/credentials/main/service_keys/record_refused_key.rs b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/record_refused_key.rs new file mode 100644 index 0000000000..3f5b49790c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/record_refused_key.rs @@ -0,0 +1,35 @@ +//! A known key that is refused is audited under its service account, so its owner sees the failed calls. + +use serde_json::json; +use uuid::Uuid; + +use crate::credentials::main::audit::append_audit::append_audit; +use crate::credentials::models::AuditContext; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit}; +use crate::store::models::{ControlStore, TransactionMode}; + +/// Records that `key_id` of `principal_id` was refused for `reason`, as that service account. +pub(crate) async fn record_refused_key( + store: &ControlStore, + context: &AuditContext, + (principal_id, key_id, reason): (Uuid, Uuid, &str), +) -> Result<(), ControlError> { + let context = AuditContext { + actor: format!("principal:{principal_id}"), + granting_role: "service-key".into(), + ..context.clone() + }; + let transaction = append_audit( + begin(store, TransactionMode::Write).await?, + &context, + (Uuid::now_v7(), "service_account.key_refused"), + ( + json!({"principal_id": principal_id}), + json!(null), + json!({"key_id": key_id, "allowed": false, "reason": reason}), + ), + ) + .await?; + commit(transaction).await +} diff --git a/crates/sqlbuild-orchestration/src/credentials/main/service_keys/record_service_key_use.rs b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/record_service_key_use.rs new file mode 100644 index 0000000000..2d269b6ba6 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/credentials/main/service_keys/record_service_key_use.rs @@ -0,0 +1,36 @@ +//! A key's last use moves forward at most once a minute, so busy callers don't write on every request. + +use chrono::{DateTime, Duration, Utc}; + +use crate::credentials::constants::KEY_USE_INTERVAL_SECONDS; +use crate::credentials::models::ServiceKeyIdentity; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit, query::query}; +use crate::store::models::{ControlStore, Parameter, TransactionMode}; + +/// Records that `identity`'s key served a request at `now`, unless that was already recorded within the interval. +pub(crate) async fn record_service_key_use( + store: &ControlStore, + identity: ServiceKeyIdentity, + now: DateTime, +) -> Result<(), ControlError> { + let interval = Duration::seconds(KEY_USE_INTERVAL_SECONDS); + if identity + .last_used_at + .is_some_and(|last| now - last < interval) + { + return Ok(()); + } + let (transaction, _) = query( + begin(store, TransactionMode::Write).await?, + "UPDATE sqb_service_account_keys SET last_used_at=$1 WHERE key_id=$2 \ + AND (last_used_at IS NULL OR last_used_at<$3)", + vec![ + Parameter::Time(now), + Parameter::Id(identity.key_id), + Parameter::Time(now - interval), + ], + ) + .await?; + commit(transaction).await +} diff --git a/crates/sqlbuild-orchestration/src/credentials/main/sessions/set_password.rs b/crates/sqlbuild-orchestration/src/credentials/main/sessions/set_password.rs index f1b13e5878..979c317d5b 100644 --- a/crates/sqlbuild-orchestration/src/credentials/main/sessions/set_password.rs +++ b/crates/sqlbuild-orchestration/src/credentials/main/sessions/set_password.rs @@ -29,13 +29,13 @@ pub async fn set_password( transaction, "SELECT c.credential_id FROM sqb_principals p \ LEFT JOIN sqb_password_credentials c ON c.principal_id=p.principal_id \ - WHERE p.principal_id=$1 AND p.disabled_at IS NULL", + WHERE p.principal_id=$1 AND p.disabled_at IS NULL AND NOT EXISTS (SELECT 1 FROM sqb_service_accounts s WHERE s.principal_id=p.principal_id)", vec![Parameter::Id(principal_id)], ) .await?; if rows.is_empty() { return Err(ControlError::Invalid( - "password requires an active person".into(), + "password requires an active person; service accounts sign in only with keys".into(), )); } if let Some((id, session_id)) = expected { diff --git a/crates/sqlbuild-orchestration/src/credentials/models.rs b/crates/sqlbuild-orchestration/src/credentials/models.rs index b5b987e0f6..18e64ce569 100644 --- a/crates/sqlbuild-orchestration/src/credentials/models.rs +++ b/crates/sqlbuild-orchestration/src/credentials/models.rs @@ -42,6 +42,17 @@ pub struct SecurityAuditEvent { /// The person's name when `actor` is a principal; person reads set it, exports leave it out. #[serde(default, skip_serializing_if = "Option::is_none")] pub actor_name: Option, + /// Whether `actor` is a person or a service account; set with `actor_name`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub actor_kind: Option, +} + +/// A principal signs in as a person, or calls with an API key as a service account. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum PrincipalKind { + Person, + Service, } /// A person as administrators see them: how they sign in, their SSO groups and live sessions. @@ -175,6 +186,8 @@ pub enum Action { RunAdhoc, #[serde(rename = "connection.test")] ConnectionTest, + #[serde(rename = "location.republish")] + LocationRepublish, #[serde(rename = "user.manage")] UserManage, #[serde(rename = "role.assign")] @@ -428,3 +441,161 @@ pub(crate) struct StoredToken { pub(crate) secret_hash: String, pub(crate) expires_at: DateTime, } + +/// How a service account key came to be: made by SQLBuild, or chosen with the CLI's `--key-from-env`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ServiceKeyOrigin { + Issued, + Imported, +} + +impl ServiceKeyOrigin { + /// The stored text, as the store's check constraint names it. + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::Issued => "issued", + Self::Imported => "imported", + } + } +} + +/// One working key of a service account; never the key itself. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct ServiceKeySummary { + pub key_id: Uuid, + /// The non-secret start of the key, e.g. `sqbk_Q7m2xT`. + pub prefix: String, + pub origin: ServiceKeyOrigin, + pub created_at: DateTime, + /// Who made it; none when the control-store owner did, with the CLI. + pub created_by: Option, + /// The last request this key authenticated that wasn't refused. + pub last_used_at: Option>, + /// When a key replaced by a rotation stops working; none for the current key. + pub expires_at: Option>, +} + +/// A service account as administrators see it: its role, state and working keys. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct ServiceAccountSummary { + pub principal_id: Uuid, + pub name: String, + pub description: Option, + /// Its built-in role everywhere; none when it holds no installation-wide built-in role. + pub role: Option, + pub created_at: DateTime, + pub created_by: Option, + /// While set, every key of the account is refused. + pub disabled_at: Option>, + /// The newest last use of any of its keys, stopped ones included. + pub last_used_at: Option>, + /// Keys that work, or will once the account is enabled: the current key first, then one still in its overlap. + pub keys: Vec, +} + +/// A service account with a key that is returned only this once; the store keeps only its hash. +#[derive(Clone, Serialize, Deserialize, utoipa::ToSchema)] +pub struct IssuedServiceKey { + pub account: ServiceAccountSummary, + pub key: String, +} + +/// A service account to add: its name, what uses it, and its built-in role everywhere. +#[derive(Clone, Debug, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct NewServiceAccount { + pub name: String, + #[serde(default)] + pub description: Option, + pub role: BuiltinRole, +} + +/// A rotation: how many minutes the replaced key keeps working, at most a day; none or 0 stops it at once. +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct ServiceKeyRotation { + #[serde(default)] + pub overlap_minutes: Option, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct ServiceAccountState { + pub disabled: bool, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct ServiceAccountRole { + pub role: BuiltinRole, +} + +/// Who changes a service account: an authenticated person, whose permissions are checked, or the control-store owner. +#[derive(Clone, Copy, Debug)] +pub enum ServiceAccountAuthority { + Owner, + Person(Uuid), +} + +/// The service account a request's key authenticated, and when that key was last recorded as used. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ServiceKeyIdentity { + pub(crate) principal_id: Uuid, + pub(crate) key_id: Uuid, + pub(crate) last_used_at: Option>, +} + +/// A stored key as authentication reads it, with whether its account is disabled. +#[derive(Debug, Deserialize)] +pub(crate) struct ServiceKeyState { + pub(crate) key_id: Uuid, + pub(crate) principal_id: Uuid, + pub(crate) expires_at: Option>, + pub(crate) revoked_at: Option>, + pub(crate) last_used_at: Option>, + pub(crate) disabled_at: Option>, +} + +/// A key made for a service account, returned only once, and its non-secret prefix. +pub(crate) struct NewServiceKey { + pub(crate) key: String, + pub(crate) prefix: String, + pub(crate) origin: ServiceKeyOrigin, +} + +/// What a presented key turned out to be. +#[derive(Clone, Copy, Debug)] +pub(crate) enum ServiceKeyCheck { + Accepted(ServiceKeyIdentity), + /// A key the store knows, refused because its account is disabled or it was stopped or expired. + Refused { + principal_id: Uuid, + key_id: Uuid, + reason: &'static str, + }, + Unknown, +} + +/// Never prints the key, so a debug log can't leak it. +impl std::fmt::Debug for IssuedServiceKey { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("IssuedServiceKey") + .field("account", &self.account) + .field("key", &"[redacted]") + .finish() + } +} + +/// Never prints the key, so a debug log can't leak it. +impl std::fmt::Debug for NewServiceKey { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("NewServiceKey") + .field("key", &"[redacted]") + .field("prefix", &self.prefix) + .field("origin", &self.origin) + .finish() + } +} diff --git a/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs b/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs index 6ca0dca753..0533de9dcc 100644 --- a/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs +++ b/crates/sqlbuild-orchestration/src/declarations/_helpers/trigger_scope.rs @@ -1,4 +1,4 @@ -//! A trigger override's permission scope is every node a schedule's job or group writes, or every node of a sensor's target. +//! A trigger override's permission scope is every node a schedule's job or group writes, or every node of the target for a sensor, and to pause or resume a schedule whose job can't be read. use std::collections::BTreeSet; @@ -6,7 +6,7 @@ use uuid::Uuid; use crate::authorization::main::decisions::refuse_unknown::refuse_unknown; use crate::credentials::models::{Action, AuditContext, PermissionScope}; -use crate::declarations::models::{TriggerChange, TriggerChangeRequest}; +use crate::declarations::models::{JobDefinition, TriggerChange, TriggerChangeRequest}; use crate::runs::main::requests::frozen_job_request::frozen_job_request; use crate::runs::models::JobRunRequest; use crate::snapshots::main::write_sets::job_write_set::job_write_set; @@ -29,7 +29,10 @@ pub(crate) async fn trigger_scope( | TriggerChange::SkipEvent { .. } => Action::SensorResetCursor, }; let (transaction, rows) = query(transaction, - "SELECT location_id,target,job_key FROM sqb_triggers WHERE trigger_id=$1 AND removed_in_snapshot_id IS NULL", + "SELECT t.location_id,t.target,t.job_key,j.definition_json AS job_definition FROM sqb_triggers t \ + LEFT JOIN sqb_current_snapshots c ON c.location_id=t.location_id AND c.target=t.target \ + LEFT JOIN sqb_jobs j ON j.location_id=t.location_id AND j.target=t.target AND j.job_key=t.job_key AND j.snapshot_id=c.snapshot_id \ + WHERE t.trigger_id=$1 AND t.removed_in_snapshot_id IS NULL", vec![Parameter::Id(request.trigger_id)]).await?; let Some(row) = rows.first() else { return refuse_unknown( @@ -43,7 +46,10 @@ pub(crate) async fn trigger_scope( let location_id: Uuid = serde_json::from_value(row["location_id"].clone()) .map_err(|error| ControlError::Invalid(error.to_string()))?; let target: String = row["target"].as_str().unwrap_or_default().into(); - let Some(job_key) = row["job_key"].as_str() else { + let without_job: bool = matches!(request.change, TriggerChange::Enable | TriggerChange::Pause) + && !row["job_definition"].is_null() + && serde_json::from_value::(row["job_definition"].clone()).is_err(); + let Some(job_key) = row["job_key"].as_str().filter(|_| !without_job) else { let (transaction, nodes) = target_nodes(transaction, (location_id, &target)).await?; return Ok(( transaction, @@ -85,7 +91,7 @@ pub(crate) async fn trigger_scope( )) } -/// Every node the target's current snapshot publishes: a sensor may start any of its jobs. +/// Every node the target's current snapshot publishes: a sensor may start any of its jobs, and a job that can't be read may write any of its nodes. async fn target_nodes( transaction: ControlTransaction, (location_id, target): (Uuid, &str), diff --git a/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs b/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs index f8831a18fc..ce7c24e883 100644 --- a/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs +++ b/crates/sqlbuild-orchestration/src/declarations/main/change_person_trigger.rs @@ -1,4 +1,4 @@ -//! A trigger override needs its permission on every node the trigger's current job or group writes. +//! A trigger override needs its permission on every node of the trigger's scope. use serde_json::json; use uuid::Uuid; diff --git a/crates/sqlbuild-orchestration/src/dev_events/models.rs b/crates/sqlbuild-orchestration/src/dev_events/models.rs index 3362d969e1..ef60d461c7 100644 --- a/crates/sqlbuild-orchestration/src/dev_events/models.rs +++ b/crates/sqlbuild-orchestration/src/dev_events/models.rs @@ -2,6 +2,8 @@ use serde::{Deserialize, Serialize}; +use crate::platform::models::MissingProviderSetting; + /// One step of publishing a location generation. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -27,11 +29,15 @@ pub struct SourcePosition { pub column: u32, } -/// A provider whose unset secrets stop the runs that use it: the variables it reads, never their values. +/// A provider whose unset secrets stop the runs that use it: where each is declared and what needs it, never a value. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct UnsetProviderSecrets { pub provider: String, - pub variables: Vec, + /// The provider's file, relative to the project directory. + pub path: String, + pub settings: Vec, + /// The node keys that use the provider, then those that read them. + pub needed_by: Vec, } /// What happened in the location child. @@ -71,7 +77,11 @@ pub enum DevEvent { /// The providers the latest provider-secrets health shows missing secrets the target doesn't allow to miss; empty once none is. MissingSecrets { providers: Vec, + /// The env file the location loads, relative to the project; `None` when it loads none. + env_file: Option, }, + /// The discovered sets a publication used, summarised for the ready card. + Discovered { summary: String }, } /// What `sqb dev` asks its location child to do, one JSON line each on the child's stdin. diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/digest.rs b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/digest.rs new file mode 100644 index 0000000000..d2a79f6b4d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/digest.rs @@ -0,0 +1,14 @@ +//! The digest that says whether a discover function's result changed. + +use sqlbuild_recall::records::main::sha256_hex::sha256_hex; + +use crate::discovered_sets::models::DiscoveredResult; +use crate::snapshots::main::publication::canonical_json_bytes::canonical_json_bytes; +use crate::store::errors::ControlError; + +/// The SHA-256 of `result`'s canonical JSON: its items in order, its tags and `max_parallel`. +pub(crate) fn discovered_digest(result: &DiscoveredResult) -> Result { + let value = + serde_json::to_value(result).map_err(|error| ControlError::Invalid(error.to_string()))?; + Ok(sha256_hex(&canonical_json_bytes(&value)?)) +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/item_graph.rs b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/item_graph.rs new file mode 100644 index 0000000000..f543f713d8 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/item_graph.rs @@ -0,0 +1,59 @@ +//! The item IDs of a set and the items each one waits on inside it. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::discovered_sets::models::{DiscoveredResult, DiscoveredSet, ItemDependency}; + +/// Each item's ID with the IDs of the items of its set it waits on. +pub(crate) fn item_parents(result: &DiscoveredResult) -> BTreeMap<&str, BTreeSet<&str>> { + let mut parents: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); + for item in &result.items { + let of: &mut BTreeSet<&str> = parents.entry(item.id.as_str()).or_default(); + for dependency in &item.depends_on { + if let ItemDependency::Item(id) = dependency { + of.insert(id.as_str()); + } + } + } + parents +} + +/// An item ID on a dependency cycle, if any. +pub(crate) fn cycle_member<'a>(parents: &BTreeMap<&'a str, BTreeSet<&'a str>>) -> Option<&'a str> { + let mut waiting: BTreeMap<&str, usize> = + parents.iter().map(|(id, of)| (*id, of.len())).collect(); + let mut ready: Vec<&str> = waiting + .iter() + .filter(|(_, count)| **count == 0) + .map(|(id, _)| *id) + .collect(); + while let Some(done) = ready.pop() { + waiting.remove(done); + for (id, of) in parents { + if of.contains(done) + && let Some(count) = waiting.get_mut(id) + { + *count -= 1; + if *count == 0 { + ready.push(id); + } + } + } + } + waiting.keys().next().copied() +} + +/// How many items a set serves: its newest result, or its last good one after a failure. +pub(crate) fn item_count(set: &DiscoveredSet) -> u64 { + set.result.as_ref().map_or(0, |result| { + u64::try_from(result.items.len()).unwrap_or(u64::MAX) + }) +} + +/// `1 item` or `n items`. +pub(crate) fn item_count_text(items: u64) -> String { + match items { + 1 => "1 item".to_owned(), + _ => format!("{items} items"), + } +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/mod.rs new file mode 100644 index 0000000000..45cb92f34f --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/mod.rs @@ -0,0 +1,3 @@ +pub(crate) mod digest; +pub(crate) mod item_graph; +pub(crate) mod problems; diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/problems.rs b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/problems.rs new file mode 100644 index 0000000000..5a68f5de5e --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/_helpers/problems.rs @@ -0,0 +1,61 @@ +//! Why a discover function's result cannot be a set: no items, bad or repeated IDs, unknown items or a cycle. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::discovered_sets::_helpers::item_graph::{cycle_member, item_parents}; +use crate::discovered_sets::constants::{ITEM_ID_MAX_CHARS, ITEM_ID_PUNCTUATION}; +use crate::discovered_sets::models::DiscoveredResult; + +/// The first problem with `result`, or `None` when its items form a set. +pub(crate) fn discovered_problem(result: &DiscoveredResult) -> Option { + if result.items.is_empty() { + return Some("the discover function returned no items".to_owned()); + } + let mut seen: BTreeSet<&str> = BTreeSet::new(); + for item in &result.items { + if let Some(problem) = id_problem(&item.id) { + return Some(problem); + } + if !seen.insert(&item.id) { + return Some(format!("item ID '{}' appears more than once", item.id)); + } + } + let parents: BTreeMap<&str, BTreeSet<&str>> = item_parents(result); + for (id, of) in &parents { + if let Some(missing) = of.iter().find(|parent| !seen.contains(*parent)) { + return Some(format!( + "item '{id}' depends on '{missing}', which is not an item of the set" + )); + } + if of.contains(id) { + return Some(format!("item '{id}' depends on itself")); + } + } + if let Some(member) = cycle_member(&parents) { + return Some(format!("item '{member}' is on a dependency cycle")); + } + if result.max_parallel == Some(0) { + return Some("max_parallel must be at least 1".to_owned()); + } + None +} + +/// Why `id` is not an item ID: empty, too long, or using a character outside `[A-Za-z0-9_.:-]`. +fn id_problem(id: &str) -> Option { + if id.is_empty() { + return Some("an item ID is empty".to_owned()); + } + if id.chars().count() > ITEM_ID_MAX_CHARS { + return Some(format!( + "item ID '{id}' is longer than {ITEM_ID_MAX_CHARS} characters" + )); + } + let allowed = |character: char| { + character.is_ascii_alphanumeric() || ITEM_ID_PUNCTUATION.contains(&character) + }; + id.chars() + .find(|character| !allowed(*character)) + .map(|character| { + format!("item ID '{id}' uses '{character}'; IDs use only letters, digits and _ . : -") + }) +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/constants.rs b/crates/sqlbuild-orchestration/src/discovered_sets/constants.rs new file mode 100644 index 0000000000..e21db6699c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/constants.rs @@ -0,0 +1,18 @@ +//! Limits and names of discovered sets. + +/// The snapshot document that keeps every discovered set. +pub const DISCOVERED_DOCUMENT: &str = "discovered"; +/// The longest item ID, in characters. +pub const ITEM_ID_MAX_CHARS: usize = 200; +/// The characters an item ID may use besides ASCII letters and digits. +pub const ITEM_ID_PUNCTUATION: [char; 4] = ['_', '.', ':', '-']; +/// What stands for the item ID in the one node of a set that was never discovered. +pub const PLACEHOLDER_ITEM: &str = "*"; +/// The shortest `check_every`, in seconds. +pub const MIN_CHECK_EVERY_SECONDS: u64 = 60; +/// Seconds per `check_every` unit, largest first. +pub const CHECK_EVERY_UNITS: [(char, u64); 4] = [('d', 86_400), ('h', 3_600), ('m', 60), ('s', 1)]; +/// The key that makes a location runtime request a publication. +pub const GENERATION_KEY: &str = "generation"; +/// The key that makes a location runtime request a `check_every` check. +pub const CHECK_DISCOVERED_KEY: &str = "check_discovered"; diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs new file mode 100644 index 0000000000..a852097f7c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovered_readback.rs @@ -0,0 +1,30 @@ +//! Each discovered set as a deploy reads it back: status, times, digest, tags and item count. + +use std::collections::BTreeMap; + +use crate::discovered_sets::_helpers::item_graph::item_count; +use crate::discovered_sets::models::DiscoveredResult; +use crate::discovered_sets::types::DiscoveredSets; +use crate::platform::models::DiscoveredSetReadback; + +/// The sets by name, each with the tags of the result it serves. +pub fn discovered_readback(sets: &DiscoveredSets) -> Vec { + sets.iter() + .map(|(name, set)| DiscoveredSetReadback { + name: name.clone(), + status: set.status, + fetched_at: set.fetched_at, + last_good_at: set.last_good_at, + digest: set.digest.clone(), + tags: set.result.as_ref().map(served_tags).unwrap_or_default(), + items: item_count(set), + error: set.error.clone(), + check_every_seconds: set.check_every_seconds, + }) + .collect() +} + +/// The tags of the result a set serves. +fn served_tags(result: &DiscoveredResult) -> BTreeMap { + result.tags.clone() +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/discovery_health.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovery_health.rs new file mode 100644 index 0000000000..1efad8a0dc --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovery_health.rs @@ -0,0 +1,18 @@ +//! What a location's health reports of its discovered sets. + +use crate::discovered_sets::_helpers::item_graph::item_count; +use crate::discovered_sets::types::DiscoveredSets; +use crate::platform::models::DiscoveryHealth; + +/// Each set's status, error, item count and last good time, by name. +pub fn discovery_health(sets: &DiscoveredSets) -> Vec { + sets.iter() + .map(|(name, set)| DiscoveryHealth { + name: name.clone(), + status: set.status, + error: set.error.clone(), + items: item_count(set), + last_good_at: set.last_good_at, + }) + .collect() +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/discovery_summary.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovery_summary.rs new file mode 100644 index 0000000000..a3e40157bd --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/discovery_summary.rs @@ -0,0 +1,30 @@ +//! The line `sqb dev`'s ready card shows of a publication's discovered sets. + +use crate::discovered_sets::_helpers::item_graph::{item_count, item_count_text}; +use crate::discovered_sets::models::DiscoveredSetStatus; +use crate::discovered_sets::types::DiscoveredSets; + +/// `orders_plan 27 items · returns_plan ✗ ssh timeout (using last good, 11 items)`; `None` without sets. +pub fn discovery_summary(sets: &DiscoveredSets) -> Option { + let parts: Vec = sets + .iter() + .map(|(name, set)| { + let items: u64 = item_count(set); + let error: &str = set.error.as_deref().unwrap_or("failed"); + match (set.status, &set.result) { + (DiscoveredSetStatus::Ok, _) => format!("{name} {}", item_count_text(items)), + (DiscoveredSetStatus::Failed, Some(_)) => { + format!( + "{name} \u{2717} {error} (using last good, {})", + item_count_text(items) + ) + } + (DiscoveredSetStatus::Failed, None) => { + format!("{name} \u{2717} {error} (never discovered)") + } + (DiscoveredSetStatus::Never, _) => format!("{name} not discovered"), + } + }) + .collect(); + (!parts.is_empty()).then(|| parts.join(" \u{b7} ")) +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/item_node_name.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/item_node_name.rs new file mode 100644 index 0000000000..cf176e3779 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/item_node_name.rs @@ -0,0 +1,8 @@ +//! The node name of one item of an asset's set: `[]`. + +use crate::discovered_sets::constants::PLACEHOLDER_ITEM; + +/// `asset[item]`; with no item, the placeholder `asset[*]` of a set that was never discovered. +pub fn item_node_name(asset: &str, item: Option<&str>) -> String { + format!("{asset}[{}]", item.unwrap_or(PLACEHOLDER_ITEM)) +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/item_roots.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/item_roots.rs new file mode 100644 index 0000000000..e7c0321b7f --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/item_roots.rs @@ -0,0 +1,15 @@ +//! The roots of a set: the items that wait on no other item of it. + +use std::collections::BTreeSet; + +use crate::discovered_sets::_helpers::item_graph::item_parents; +use crate::discovered_sets::models::DiscoveredResult; + +/// The IDs of the items of `result` that depend on no other item of it. +pub fn item_roots(result: &DiscoveredResult) -> BTreeSet { + item_parents(result) + .into_iter() + .filter(|(_, parents)| parents.is_empty()) + .map(|(id, _)| id.to_owned()) + .collect() +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/mod.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/mod.rs new file mode 100644 index 0000000000..e1dffa8eb1 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/mod.rs @@ -0,0 +1,11 @@ +pub mod discovered_readback; +pub mod discovery_health; +pub mod discovery_summary; +pub mod item_node_name; +pub mod item_roots; +pub mod never_discovered; +pub mod parse_check_every; +pub mod record_attempt; +pub mod remote_discovered_sets; +pub mod result_changed; +pub mod unknown_dependency; diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/never_discovered.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/never_discovered.rs new file mode 100644 index 0000000000..c3b490cbe5 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/never_discovered.rs @@ -0,0 +1,16 @@ +//! A set no attempt has reached, such as every set of a compile outside a location. + +use crate::discovered_sets::models::{DiscoveredSet, DiscoveredSetStatus}; + +/// A set with no attempt and no result, checked every `check_every_seconds` if set. +pub fn never_discovered(check_every_seconds: Option) -> DiscoveredSet { + DiscoveredSet { + status: DiscoveredSetStatus::Never, + fetched_at: None, + last_good_at: None, + digest: None, + error: None, + check_every_seconds, + result: None, + } +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/parse_check_every.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/parse_check_every.rs new file mode 100644 index 0000000000..09868fdef1 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/parse_check_every.rs @@ -0,0 +1,37 @@ +//! A `check_every` interval such as `15m` or `1h30m`, in seconds. + +use crate::discovered_sets::constants::{CHECK_EVERY_UNITS, MIN_CHECK_EVERY_SECONDS}; + +/// `text` as whole seconds: amounts in `d`, `h`, `m` and `s`, largest unit first, at least a minute. +pub fn parse_check_every(text: &str) -> Result { + let refused = || { + format!( + "check_every '{text}' is not an interval such as \"15m\" or \"1h30m\" of at least {MIN_CHECK_EVERY_SECONDS} seconds" + ) + }; + let mut seconds: u64 = 0; + let mut digits: String = String::new(); + let mut next_unit: usize = 0; + for character in text.trim().chars() { + if character.is_ascii_digit() { + digits.push(character); + continue; + } + let position = CHECK_EVERY_UNITS[next_unit..] + .iter() + .position(|(unit, _)| *unit == character) + .ok_or_else(refused)?; + let amount: u64 = digits.parse().map_err(|_| refused())?; + let (_, unit_seconds) = CHECK_EVERY_UNITS[next_unit + position]; + seconds = amount + .checked_mul(unit_seconds) + .and_then(|added| seconds.checked_add(added)) + .ok_or_else(refused)?; + digits.clear(); + next_unit += position + 1; + } + if !digits.is_empty() || seconds < MIN_CHECK_EVERY_SECONDS { + return Err(refused()); + } + Ok(seconds) +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/record_attempt.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/record_attempt.rs new file mode 100644 index 0000000000..931dbd698a --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/record_attempt.rs @@ -0,0 +1,46 @@ +//! A set after one attempt: a success replaces its result, a failure keeps the last good one, its error without NUL, which PostgreSQL refuses. + +use chrono::{DateTime, Utc}; +use sqlbuild_core::redaction::main::redact_text::redact_text; + +use crate::discovered_sets::_helpers::digest::discovered_digest; +use crate::discovered_sets::_helpers::problems::discovered_problem; +use crate::discovered_sets::models::{DiscoveredResult, DiscoveredSet, DiscoveredSetStatus}; + +/// `previous` after an attempt at `now` that returned `attempt`; a result that is not a valid set fails like an error. +pub fn record_attempt( + previous: Option<&DiscoveredSet>, + attempt: Result, + (now, check_every_seconds): (DateTime, Option), +) -> DiscoveredSet { + let checked = attempt.and_then(|result| match discovered_problem(&result) { + Some(problem) => Err(problem), + None => discovered_digest(&result) + .map(|digest| (result, digest)) + .map_err(|error| error.to_string()), + }); + match checked { + Ok((result, digest)) => DiscoveredSet { + status: DiscoveredSetStatus::Ok, + fetched_at: Some(now), + last_good_at: Some(now), + digest: Some(digest), + error: None, + check_every_seconds, + result: Some(result), + }, + Err(error) => DiscoveredSet { + status: DiscoveredSetStatus::Failed, + fetched_at: Some(now), + last_good_at: previous.and_then(|set| set.last_good_at), + digest: previous.and_then(|set| set.digest.clone()), + error: Some(if error.contains('\0') { + redact_text(&error) + } else { + error + }), + check_every_seconds, + result: previous.and_then(|set| set.result.clone()), + }, + } +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/remote_discovered_sets.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/remote_discovered_sets.rs new file mode 100644 index 0000000000..b6bd89cf39 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/remote_discovered_sets.rs @@ -0,0 +1,47 @@ +//! The discovered sets of a location's current snapshot on the server, read with its credential. + +use reqwest::StatusCode; +use serde_json::Value; +use uuid::Uuid; + +use crate::api::errors::ClientError; +use crate::api::main::client_response::client_response; +use crate::api::main::connect_client::connect_client; +use crate::discovered_sets::constants::DISCOVERED_DOCUMENT; +use crate::discovered_sets::types::DiscoveredSets; + +/// The sets the current snapshot of `target` saved; empty when there is none or it saved none. +pub async fn remote_discovered_sets( + (server_url, bearer): (&str, &str), + (location_id, target): (Uuid, &str), +) -> Result { + let connection = connect_client(server_url, bearer)?; + let url = connection.endpoint(&[ + "api", + "locations", + &location_id.to_string(), + "targets", + target, + "snapshots", + ])?; + let current: Value = match client_response(connection.client.get(url)).await { + Ok(current) => current, + Err(ClientError::Rejected(status)) if status == StatusCode::NOT_FOUND => { + return Ok(DiscoveredSets::new()); + } + Err(error) => return Err(error), + }; + current["documents"] + .get(DISCOVERED_DOCUMENT) + .cloned() + .map_or_else( + || Ok(DiscoveredSets::new()), + |document| { + serde_json::from_value(document).map_err(|_| { + ClientError::Configuration( + "the current snapshot's discovered sets are unreadable", + ) + }) + }, + ) +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/result_changed.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/result_changed.rs new file mode 100644 index 0000000000..c414b0dd15 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/result_changed.rs @@ -0,0 +1,9 @@ +//! Whether a fresh attempt found a different result than a set's last good one. + +use crate::discovered_sets::models::{DiscoveredSet, DiscoveredSetStatus}; + +/// True when `next` succeeded with a digest `previous` did not have; a failure never counts. +pub fn result_changed(previous: Option<&DiscoveredSet>, next: &DiscoveredSet) -> bool { + next.status == DiscoveredSetStatus::Ok + && previous.and_then(|set| set.digest.as_deref()) != next.digest.as_deref() +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/main/unknown_dependency.rs b/crates/sqlbuild-orchestration/src/discovered_sets/main/unknown_dependency.rs new file mode 100644 index 0000000000..0e6744e02f --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/main/unknown_dependency.rs @@ -0,0 +1,29 @@ +//! The first project node a set's items depend on that the project doesn't have. + +use crate::discovered_sets::models::{DiscoveredResult, ItemDependency}; + +/// Why `result` can't be a set of this project: an item depends on a node `known` rejects. +pub fn unknown_dependency( + result: &DiscoveredResult, + known: &impl Fn(&ItemDependency) -> bool, +) -> Option { + for item in &result.items { + for dependency in &item.depends_on { + let (kind, name, missing): (&str, &str, &str) = match dependency { + ItemDependency::Item(_) => continue, + ItemDependency::Model(name) => ("model", name, "have"), + ItemDependency::Source(name) => ("source", name, "have"), + ItemDependency::Seed(name) => ("seed", name, "have"), + ItemDependency::Job(set) => ("job", &set.name, "declare"), + ItemDependency::Tag(_) => continue, + }; + if !known(dependency) { + return Some(format!( + "item '{}' depends on {kind} '{name}', which the project does not {missing}", + item.id + )); + } + } + } + None +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/mod.rs b/crates/sqlbuild-orchestration/src/discovered_sets/mod.rs new file mode 100644 index 0000000000..3844a5a4f8 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/mod.rs @@ -0,0 +1,11 @@ +//! What `@discover` functions returned, kept in the snapshot so later compiles reuse it. + +pub(crate) mod _helpers; +pub mod constants; +pub mod main; +pub mod models; +pub mod types; + +#[cfg(test)] +#[path = "../../tests/discovered_sets/test_contracts.rs"] +mod tests; diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/models.rs b/crates/sqlbuild-orchestration/src/discovered_sets/models.rs new file mode 100644 index 0000000000..17aa1dac8a --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/models.rs @@ -0,0 +1,115 @@ +//! A discovered set as a discover function returns it and as the snapshot keeps it. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::discovered_sets::types::DiscoveredSets; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// One discover function's set: its newest attempt, and the last result that succeeded. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DiscoveredSet { + pub status: DiscoveredSetStatus, + /// When the newest attempt ran; `None` for a set no attempt reached. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fetched_at: Option>, + /// When `result` was fetched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_good_at: Option>, + /// The digest of `result`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub digest: Option, + /// Why the newest attempt failed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + /// How often the location checks the set for changes; `None` checks only when it publishes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub check_every_seconds: Option, + /// The last result that succeeded; `None` for a set that never did. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, +} + +/// How a set's newest attempt went. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum DiscoveredSetStatus { + /// The newest attempt succeeded. + Ok, + /// The newest attempt failed; `result`, if any, is the last good one. + Failed, + /// No attempt has run, such as a compile outside a location. + Never, +} + +/// What one discover function returned: its items, and set-wide tags and parallelism. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DiscoveredResult { + pub items: Vec, + pub tags: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_parallel: Option, +} + +/// One item: its ID, what it waits on, and the arguments its nodes are called with. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DiscoveredItem { + pub id: String, + pub depends_on: Vec, + pub args: BTreeMap, +} + +/// What an item waits on: another item of its set, or a node of the project. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", deny_unknown_fields)] +pub enum ItemDependency { + Item(String), + Model(String), + Source(String), + Seed(String), + Job(NodeSetDependency), + Tag(NodeSetDependency), +} + +/// A `job(...)` or `tag(...)` dependency of an item. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NodeSetDependency { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exclude: Option, +} + +/// What a location asks its runtime interpreter to publish, and which sets to discover again. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DiscoveryPublishRequest { + pub generation: i64, + /// The discover functions to call again; `None` calls every one. + pub rediscover: Option>, + /// The sets of the last publication, reused for every function not called again. + pub previous: DiscoveredSets, + /// Whether a set that fails with no result of its own reads its last good one from the server. + pub seed: bool, +} + +/// A location's `check_every` request: call one discover function again without publishing. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DiscoveredSetCheck { + pub check_discovered: String, + pub previous: Option, +} + +/// The runtime's reply to a check: the set after the call, and whether its result changed. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct DiscoveredSetChecked { + /// `None` when the runtime holds no compiled project, or the function no longer exists. + pub set: Option, + pub changed: bool, +} diff --git a/crates/sqlbuild-orchestration/src/discovered_sets/types.rs b/crates/sqlbuild-orchestration/src/discovered_sets/types.rs new file mode 100644 index 0000000000..552feb9406 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/discovered_sets/types.rs @@ -0,0 +1,8 @@ +//! Collections of discovered sets. + +use std::collections::BTreeMap; + +use crate::discovered_sets::models::DiscoveredSet; + +/// Every discovered set of a snapshot, by discover function name. +pub type DiscoveredSets = BTreeMap; diff --git a/crates/sqlbuild-orchestration/src/lib.rs b/crates/sqlbuild-orchestration/src/lib.rs index d72ede97ce..092a3d470a 100644 --- a/crates/sqlbuild-orchestration/src/lib.rs +++ b/crates/sqlbuild-orchestration/src/lib.rs @@ -13,8 +13,12 @@ pub mod declarations; pub mod dev_events; +pub mod discovered_sets; + pub mod platform; +pub mod run_output; + pub mod runs; pub mod scheduler; diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/mod.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/mod.rs index 0287380972..ce48446bb1 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/mod.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/mod.rs @@ -5,5 +5,6 @@ pub(crate) mod liveness; pub(crate) mod location_heartbeat; pub(crate) mod published_generation; pub(crate) mod reported_generation; +pub(crate) mod republish_status; pub(crate) mod rule_findings; pub(crate) mod work_client; diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs index b72c24378d..130cbf2554 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs @@ -17,6 +17,7 @@ pub(crate) fn reported_generation( LocationHealth::CompileFailed { generation, .. } | LocationHealth::Connection { generation, .. } | LocationHealth::ProviderSecrets { generation, .. } + | LocationHealth::Discovery { generation, .. } | LocationHealth::WarehouseSync { generation, .. } => Some(generation), LocationHealth::PoolCapped { .. } => { return Err(ControlError::Invalid( diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/republish_status.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/republish_status.rs new file mode 100644 index 0000000000..d9d3540f21 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/republish_status.rs @@ -0,0 +1,84 @@ +//! A stored republish request and its location's result, as the API reports it. + +use chrono::{DateTime, Utc}; + +use crate::platform::models::{ + LocationWork, LocationWorkOutcome, LocationWorkRecord, LocationWorkRequest, RepublishState, + RepublishStatus, +}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{ControlTransaction, Parameter}; + +/// `record` as a republish's status at `now`; `None` when it is other work. +pub(crate) fn republish_status( + record: &LocationWorkRecord, + now: DateTime, +) -> Option { + let LocationWork::Republish { requested_by } = &record.request_json.work else { + return None; + }; + let mut status = RepublishStatus { + request_id: record.request_json.request_id, + location_id: record.request_json.location_id, + target: record.request_json.target.clone(), + state: RepublishState::Pending, + requested_by: requested_by.clone(), + reason: record.request_json.reason.clone(), + requested_at: record.requested_at, + expires_at: record.expires_at, + completed_at: record.completed_at, + snapshot_id: None, + generation: None, + error: None, + }; + match record.result_json.as_ref().map(|result| &result.outcome) { + Some(LocationWorkOutcome::Published { + snapshot_id, + generation, + }) => { + status.state = RepublishState::Published; + status.snapshot_id = Some(*snapshot_id); + status.generation = Some(*generation); + } + Some(LocationWorkOutcome::PublishFailed { generation, error }) => { + status.state = RepublishState::Failed; + status.generation = Some(*generation); + status.error = Some(error.clone()); + } + Some(_) => { + status.state = RepublishState::Failed; + status.error = Some("the location could not republish".to_owned()); + } + None if record.expires_at <= now => status.state = RepublishState::Expired, + None => {} + } + Some(status) +} + +/// Whether a republish's snapshot is one this location published for the work's target; true for other outcomes. +pub(crate) async fn published_here( + transaction: ControlTransaction, + request: &LocationWorkRequest, + outcome: &LocationWorkOutcome, +) -> Result<(ControlTransaction, bool), ControlError> { + let LocationWorkOutcome::Published { + snapshot_id, + generation, + } = outcome + else { + return Ok((transaction, true)); + }; + let (transaction, rows) = query( + transaction, + "SELECT snapshot_id FROM sqb_snapshots WHERE snapshot_id=$1 AND location_id=$2 AND target=$3 AND generation=$4", + vec![ + Parameter::Id(*snapshot_id), + Parameter::Id(request.location_id), + Parameter::Text(request.target.clone()), + Parameter::Integer(*generation), + ], + ) + .await?; + Ok((transaction, !rows.is_empty())) +} diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs index 24869cbae3..5750dbc598 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs @@ -14,6 +14,7 @@ use crate::platform::constants::{ PLATFORM_ALERT_RETENTION_DAYS, SENSOR_EVALUATION_RETENTION_DAYS, }; use crate::platform::models::RetentionPolicies; +use crate::run_output::main::prune_run_output::prune_run_output; use crate::runs::constants::{RUN_LOG_DIGEST_CHUNK, RUN_LOG_RETENTION_BATCH}; use crate::runs::models::RunLogRetention; use crate::snapshots::main::publication::prune_snapshots::prune_snapshots; @@ -77,10 +78,16 @@ pub(crate) async fn retain( snapshots, run_logs, state_history, + run_output, }: RetentionPolicies, sinks: &[String], ) -> Result { prune_run_logs(store, run_logs).await?; + if let Some((output, days)) = &run_output { + while prune_run_output(store, output, *days).await > 0 { + tokio::task::yield_now().await; + } + } prune_snapshots(store, snapshots).await?; while prune_statistics(store, statistics).await? == MAX_HISTORY_RECORDS { tokio::task::yield_now().await; diff --git a/crates/sqlbuild-orchestration/src/platform/constants.rs b/crates/sqlbuild-orchestration/src/platform/constants.rs index 7b2d8adb10..68208c86af 100644 --- a/crates/sqlbuild-orchestration/src/platform/constants.rs +++ b/crates/sqlbuild-orchestration/src/platform/constants.rs @@ -60,3 +60,14 @@ pub const PLAN_ROWS_LIMIT: usize = 1000; pub(crate) const OBSERVATION_WINDOW_SECONDS: i64 = 30; /// The newest `trigger_skipped` events the live problems read; each trigger counts once. pub(crate) const SKIPPED_TRIGGER_EVENTS: i64 = 200; + +/// How long a republish request waits for a location to take it and publish. +pub(crate) const REPUBLISH_EXPIRY_SECONDS: i64 = 900; +/// A republish claim covers a full compile and publication. +pub(crate) const REPUBLISH_LEASE_SECONDS: i64 = 900; +/// The longest a republish request or read holds its response open with `wait`. +pub const MAX_REPUBLISH_WAIT_SECONDS: u64 = 60; +/// How often a waiting request reads the republish's result again. +pub(crate) const REPUBLISH_POLL_MILLISECONDS: u64 = 250; +/// The longest publish error the server keeps. +pub(crate) const MAX_PUBLISH_ERROR_CHARS: usize = 4000; diff --git a/crates/sqlbuild-orchestration/src/platform/main/installation/run_maintenance.rs b/crates/sqlbuild-orchestration/src/platform/main/installation/run_maintenance.rs index bcb4817031..0e7f46aa1e 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/installation/run_maintenance.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/installation/run_maintenance.rs @@ -34,7 +34,7 @@ pub async fn run_maintenance( Err(error) => return Err(error), } if retained_at.is_none_or(|at| at.elapsed() >= Duration::from_secs(60)) { - match retain(store, retention, &sinks).await { + match retain(store, retention.clone(), &sinks).await { Ok(retained) => { if retained != reported { report(retained); diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/mod.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/mod.rs index beaa841041..53e956ffb8 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/person_reads/mod.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/mod.rs @@ -1,4 +1,5 @@ pub mod list_person_platform_events; +pub mod read_person_discovered; pub mod read_person_plan; pub mod read_person_plan_diff; pub mod read_person_plan_rows; diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_discovered.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_discovered.rs new file mode 100644 index 0000000000..c16bbe039d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_discovered.rs @@ -0,0 +1,57 @@ +//! A target's current discovered sets as a person reads them back, for example after a deploy. + +use uuid::Uuid; + +use crate::authorization::main::decisions::begin_authorized::begin_authorized; +use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; +use crate::discovered_sets::constants::DISCOVERED_DOCUMENT; +use crate::discovered_sets::main::discovered_readback::discovered_readback; +use crate::discovered_sets::types::DiscoveredSets; +use crate::platform::models::DiscoveredReadback; +use crate::snapshots::main::reads::read_current_record::read_current_record; +use crate::snapshots::main::reads::read_snapshot_documents::read_snapshot_documents; +use crate::store::errors::ControlError; +use crate::store::main::commit::commit; +use crate::store::models::ControlStore; + +/// Each set's status, fetch time, digest and tags in the current snapshot; `None` before a publication. +pub async fn read_person_discovered( + store: &ControlStore, + credentials: (&AuditContext, Uuid), + (location_id, target): (Uuid, &str), + default_role: DefaultRole, +) -> Result, ControlError> { + let (transaction, _) = begin_authorized( + store, + credentials, + &PermissionScope::action(Action::View, Some((location_id, target))), + default_role, + ) + .await?; + let (transaction, snapshot) = read_current_record(transaction, (location_id, target)).await?; + let Some(snapshot) = snapshot else { + commit(transaction).await?; + return Ok(None); + }; + let (transaction, documents) = read_snapshot_documents( + transaction, + snapshot.snapshot_id, + Some(&[DISCOVERED_DOCUMENT]), + ) + .await?; + commit(transaction).await?; + let sets: DiscoveredSets = match documents.get(DISCOVERED_DOCUMENT) { + Some(document) => serde_json::from_value(document.clone()).map_err(|error| { + ControlError::Invalid(format!( + "the snapshot's discovered sets are unreadable: {error}" + )) + })?, + None => DiscoveredSets::new(), + }; + Ok(Some(DiscoveredReadback { + snapshot_id: snapshot.snapshot_id, + generation: snapshot.generation, + published_at: snapshot.published_at, + sets: discovered_readback(&sets), + })) +} diff --git a/crates/sqlbuild-orchestration/src/platform/main/work/call_remote_republish.rs b/crates/sqlbuild-orchestration/src/platform/main/work/call_remote_republish.rs new file mode 100644 index 0000000000..262dac0df7 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/main/work/call_remote_republish.rs @@ -0,0 +1,39 @@ +//! A keyed caller asks for a republish or reads one back over the bearer transport, HTTP or HTTPS. + +use uuid::Uuid; + +use crate::api::errors::ClientError; +use crate::api::main::client_response::client_response; +use crate::api::main::connect_client::connect_client; +use crate::platform::models::{RepublishCall, RepublishStatus}; + +/// The republish as `key`'s principal sees it after `call`; `None` when there is no such request. +pub async fn call_remote_republish( + (server_url, key): (&str, &str), + (location_id, target): (Uuid, &str), + call: RepublishCall<'_>, +) -> Result, ClientError> { + let connection = connect_client(server_url, key)?; + let location: String = location_id.to_string(); + let base = [ + "api", + "control", + "locations", + &location, + "targets", + target, + "republish", + ]; + let request = match call { + RepublishCall::Request(request) => connection + .client + .post(connection.endpoint(&base)?) + .json(request), + RepublishCall::Read { request_id, wait } => { + let request_id: String = request_id.to_string(); + let url = connection.endpoint(&[&base[..], &[request_id.as_str()]].concat())?; + connection.client.get(url).query(&[("wait", wait)]) + } + }; + client_response(request).await +} diff --git a/crates/sqlbuild-orchestration/src/platform/main/work/claim_location_work.rs b/crates/sqlbuild-orchestration/src/platform/main/work/claim_location_work.rs index b98dd0ad93..cae96d0d77 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/work/claim_location_work.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/work/claim_location_work.rs @@ -3,7 +3,7 @@ use chrono::Duration; use uuid::Uuid; -use crate::platform::constants::{PLAN_LEASE_SECONDS, WORK_LEASE_SECONDS}; +use crate::platform::constants::{PLAN_LEASE_SECONDS, REPUBLISH_LEASE_SECONDS, WORK_LEASE_SECONDS}; use crate::platform::main::installation::require_instance::require_instance; use crate::platform::main::work::read_location_work::read_location_work; use crate::platform::models::{LocationWork, LocationWorkClaim, LocationWorkPoll}; @@ -28,16 +28,18 @@ pub async fn claim_location_work( "SELECT w.request_id FROM sqb_location_work w WHERE w.location_id=$1 AND w.target=$2 \ AND w.expires_at>$3 AND w.completed_at IS NULL \ AND (w.claimed_until IS NULL OR w.claimed_until<=$3 OR w.session_id=$4) \ - AND (w.request_json->'work'->>'kind' IN ('check_connection','sync_warehouse','plan') OR EXISTS ( \ + AND (($5<>'republish_only' AND w.request_json->'work'->>'kind' IN ('check_connection','sync_warehouse','plan')) \ + OR w.request_json->'work'->>'kind'='republish' OR ($5<>'republish_only' AND EXISTS ( \ SELECT 1 FROM sqb_sensor_evaluation_events e JOIN sqb_triggers t ON t.trigger_id=e.trigger_id \ JOIN sqb_trigger_state s ON s.trigger_id=t.trigger_id JOIN sqb_scheduler_lease l ON l.name='scheduler' \ WHERE e.evaluation_id=w.request_id AND e.phase='requested' AND s.status='running' \ AND t.snapshot_id=w.snapshot_id AND t.removed_in_snapshot_id IS NULL AND l.expires_at>$3 \ AND l.epoch=CAST(e.fact_json->'request'->>'epoch' AS BIGINT) \ AND NOT EXISTS (SELECT 1 FROM sqb_sensor_evaluation_events f \ - WHERE f.evaluation_id=e.evaluation_id AND f.phase<>'requested'))) \ + WHERE f.evaluation_id=e.evaluation_id AND f.phase<>'requested')))) \ ORDER BY CASE WHEN w.request_json->'work'->>'kind'='plan' THEN 1 ELSE 0 END, w.requested_at, w.request_id LIMIT 1", - vec![Parameter::Id(location_id), Parameter::Text(poll.target.clone()), Parameter::Time(now), Parameter::Id(poll.session_id)]).await?; + vec![Parameter::Id(location_id), Parameter::Text(poll.target.clone()), Parameter::Time(now), Parameter::Id(poll.session_id), + Parameter::Text(poll.scope.as_str().to_owned())]).await?; let Some(row) = rows.first() else { commit(transaction).await?; return Ok(None); @@ -48,6 +50,7 @@ pub async fn claim_location_work( let stored = stored.ok_or_else(|| ControlError::Invalid("location work disappeared".into()))?; let lease = match &stored.record.request_json.work { LocationWork::Plan { .. } => PLAN_LEASE_SECONDS, + LocationWork::Republish { .. } => REPUBLISH_LEASE_SECONDS, LocationWork::EvaluateSensor { evaluation } => { (2 * i64::from(evaluation.definition.timeout_seconds.get())).max(WORK_LEASE_SECONDS) } diff --git a/crates/sqlbuild-orchestration/src/platform/main/work/complete_location_work.rs b/crates/sqlbuild-orchestration/src/platform/main/work/complete_location_work.rs index 558b637b6b..b35bd19dca 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/work/complete_location_work.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/work/complete_location_work.rs @@ -4,10 +4,11 @@ use serde_json::{Value, json}; use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; use uuid::Uuid; +use crate::platform::_helpers::location::republish_status::published_here; use crate::platform::_helpers::plans::plan_diffs::{ split_plan_diffs, store_plan_diffs, valid_plan_diffs, }; -use crate::platform::constants::PLAN_DOCUMENT_BYTES; +use crate::platform::constants::{MAX_PUBLISH_ERROR_CHARS, PLAN_DOCUMENT_BYTES}; use crate::platform::main::installation::require_instance::require_instance; use crate::platform::main::work::read_location_work::read_location_work; use crate::platform::models::{LocationWork, LocationWorkOutcome, LocationWorkResult}; @@ -63,7 +64,9 @@ pub async fn complete_location_work( { return Err(ControlError::Fenced); } - let valid = valid_outcome(&stored.record.request_json.work, &result.outcome); + let (transaction, published) = + published_here(transaction, &stored.record.request_json, &result.outcome).await?; + let valid = published && valid_outcome(&stored.record.request_json.work, &result.outcome); if !valid { return Err(ControlError::Invalid( "location result does not match its work".into(), @@ -78,9 +81,15 @@ pub async fn complete_location_work( Ok(true) } -/// Warehouse text in a plan's error and warnings, and a sensor's traceback, is redacted before it is compared or stored. +/// Warehouse text in a plan's error and warnings, a sensor's traceback and a publish error is redacted before it is compared or stored. fn redacted(result: &LocationWorkResult) -> LocationWorkResult { let mut result = result.clone(); + if let LocationWorkOutcome::PublishFailed { error, .. } = &mut result.outcome { + *error = redact_error_text(error) + .chars() + .take(MAX_PUBLISH_ERROR_CHARS) + .collect(); + } if let LocationWorkOutcome::SensorEvaluation { outcome: SensorFunctionOutcome::Failed { error }, } = &mut result.outcome @@ -110,7 +119,11 @@ fn valid_outcome(work: &LocationWork, outcome: &LocationWorkOutcome) -> bool { match (work, outcome) { (_, LocationWorkOutcome::Superseded {}) | (LocationWork::CheckConnection {}, LocationWorkOutcome::Connection { .. }) - | (LocationWork::SyncWarehouse {}, LocationWorkOutcome::SyncStarted {}) => true, + | (LocationWork::SyncWarehouse {}, LocationWorkOutcome::SyncStarted {}) + | (LocationWork::Republish { .. }, LocationWorkOutcome::Published { .. }) => true, + (LocationWork::Republish { .. }, LocationWorkOutcome::PublishFailed { error, .. }) => { + !error.trim().is_empty() + } (LocationWork::Plan { .. }, LocationWorkOutcome::Plan { document, .. }) => { document .as_object() diff --git a/crates/sqlbuild-orchestration/src/platform/main/work/mod.rs b/crates/sqlbuild-orchestration/src/platform/main/work/mod.rs index 797bc68998..62862388aa 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/work/mod.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/work/mod.rs @@ -1,8 +1,11 @@ pub(in crate::platform) mod _read_target_work; +pub mod call_remote_republish; pub mod claim_location_work; pub mod complete_location_work; pub mod connect_location_work; pub(crate) mod enqueue_location_work; pub mod location_work; pub(crate) mod read_location_work; +pub mod read_republish; pub mod request_location_work; +pub mod request_republish; diff --git a/crates/sqlbuild-orchestration/src/platform/main/work/read_republish.rs b/crates/sqlbuild-orchestration/src/platform/main/work/read_republish.rs new file mode 100644 index 0000000000..f5098530d0 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/main/work/read_republish.rs @@ -0,0 +1,53 @@ +//! A republish's state as its requester or another person allowed to republish reads it. + +use std::time::Duration; + +use chrono::Utc; +use uuid::Uuid; + +use crate::authorization::main::decisions::authorize_person::authorize_person; +use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; +use crate::platform::_helpers::location::republish_status::republish_status; +use crate::platform::constants::{MAX_REPUBLISH_WAIT_SECONDS, REPUBLISH_POLL_MILLISECONDS}; +use crate::platform::main::work::_read_target_work::read_target_work; +use crate::platform::models::{RepublishState, RepublishStatus}; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit}; +use crate::store::models::{ControlStore, TransactionMode}; + +/// The target's republish, read again until it finishes or `wait` (capped) seconds pass. +pub async fn read_republish( + store: &ControlStore, + (context, credentials): (&AuditContext, Option), + (location_id, target, request_id): (Uuid, &str, Uuid), + wait: u64, +) -> Result, ControlError> { + if let Some(principal_id) = credentials { + let (transaction, _) = authorize_person( + begin(store, TransactionMode::Write).await?, + (context, principal_id), + &PermissionScope::action(Action::LocationRepublish, Some((location_id, target))), + DefaultRole::None, + ) + .await?; + commit(transaction).await?; + } + let deadline = + tokio::time::Instant::now() + Duration::from_secs(wait.min(MAX_REPUBLISH_WAIT_SECONDS)); + loop { + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, record) = + read_target_work(transaction, (location_id, target, request_id)).await?; + commit(transaction).await?; + let status: Option = + record.and_then(|record| republish_status(&record, Utc::now())); + let pending: bool = status + .as_ref() + .is_some_and(|status| status.state == RepublishState::Pending); + let next = tokio::time::Instant::now() + Duration::from_millis(REPUBLISH_POLL_MILLISECONDS); + if !pending || next > deadline { + return Ok(status); + } + tokio::time::sleep_until(next).await; + } +} diff --git a/crates/sqlbuild-orchestration/src/platform/main/work/request_location_work.rs b/crates/sqlbuild-orchestration/src/platform/main/work/request_location_work.rs index 78e70d3754..f5a8ad6f7c 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/work/request_location_work.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/work/request_location_work.rs @@ -30,6 +30,11 @@ pub async fn request_location_work( "plans must be requested by a person on the current publication".into(), )); } + LocationWork::Republish { .. } => { + return Err(ControlError::Invalid( + "a republish is requested with its own permission".into(), + )); + } LocationWork::CheckConnection {} | LocationWork::SyncWarehouse {} => {} } if request.target.trim().is_empty() diff --git a/crates/sqlbuild-orchestration/src/platform/main/work/request_republish.rs b/crates/sqlbuild-orchestration/src/platform/main/work/request_republish.rs new file mode 100644 index 0000000000..7318ba8f3d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/main/work/request_republish.rs @@ -0,0 +1,82 @@ +//! A person asks a location to compile and publish again; the request names them for the location. + +use chrono::Duration; +use uuid::Uuid; + +use crate::authorization::main::decisions::authorize_person::authorize_person; +use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; +use crate::platform::constants::REPUBLISH_EXPIRY_SECONDS; +use crate::platform::main::work::enqueue_location_work::enqueue_location_work; +use crate::platform::main::work::read_location_work::read_location_work; +use crate::platform::models::{LocationWork, LocationWorkRequest, PersonWorkRequest}; +use crate::store::errors::ControlError; +use crate::store::main::begin::begin; +use crate::store::main::commit::commit; +use crate::store::main::query::query; +use crate::store::models::{ControlStore, Parameter, TransactionMode}; + +/// Queue a republish of `target`; `false` when this request ID was already queued by the same caller. +pub async fn request_republish( + store: &ControlStore, + (context, credentials): (&AuditContext, Option), + (location_id, target): (Uuid, &str), + request: &PersonWorkRequest, +) -> Result { + if target.trim().is_empty() || request.reason.trim().is_empty() { + return Err(ControlError::Invalid( + "a republish needs a target and a reason".into(), + )); + } + let transaction = begin(store, TransactionMode::Write).await?; + let (transaction, context, requested_by) = match credentials { + Some(principal_id) => { + let (transaction, context) = authorize_person( + transaction, + (context, principal_id), + &PermissionScope::action(Action::LocationRepublish, Some((location_id, target))), + DefaultRole::None, + ) + .await?; + let (transaction, rows) = query( + transaction, + "SELECT name FROM sqb_principals WHERE principal_id=$1", + vec![Parameter::Id(principal_id)], + ) + .await?; + let name: String = rows + .first() + .and_then(|row| row["name"].as_str()) + .map_or_else(|| context.actor.clone(), str::to_owned); + (transaction, context, name) + } + None => (transaction, context.clone(), context.actor.clone()), + }; + let work = LocationWorkRequest { + request_id: request.request_id, + location_id, + target: target.to_owned(), + reason: request.reason.clone(), + work: LocationWork::Republish { requested_by }, + }; + let (transaction, previous) = read_location_work(transaction, request.request_id).await?; + if let Some(previous) = previous { + if previous.record.request_json != work || previous.record.requested_by != context.actor { + return Err(ControlError::Invalid( + "location work ID already has different content or actor".into(), + )); + } + commit(transaction).await?; + return Ok(false); + } + commit( + enqueue_location_work( + transaction, + &context, + &work, + Duration::seconds(REPUBLISH_EXPIRY_SECONDS), + ) + .await?, + ) + .await?; + Ok(true) +} diff --git a/crates/sqlbuild-orchestration/src/platform/models.rs b/crates/sqlbuild-orchestration/src/platform/models.rs index d7b85a02d8..486ef3ec7a 100644 --- a/crates/sqlbuild-orchestration/src/platform/models.rs +++ b/crates/sqlbuild-orchestration/src/platform/models.rs @@ -3,6 +3,7 @@ use crate::api::models::ControlClient; use crate::credentials::models::AuditRetention; use crate::declarations::models::TriggerDefinition; +use crate::discovered_sets::models::DiscoveredSetStatus; use crate::runs::models::{RunKind, RunLogRetention, RunNodeFailure, RunOutcome}; use crate::sensors::models::{SensorEvaluationRequest, SensorFunctionOutcome}; use crate::snapshots::models::{SnapshotRecord, SnapshotRetention}; @@ -12,16 +13,19 @@ use crate::warehouse_metadata::models::{ }; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; use uuid::Uuid; /// Every retention horizon one server's maintenance role enforces. -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Debug, Default)] pub struct RetentionPolicies { pub audit: AuditRetention, pub statistics: StatisticsRetention, pub snapshots: SnapshotRetention, pub run_logs: RunLogRetention, pub state_history: StateHistoryRetention, + /// The output store and how many days a finished run's output stays in it; `None` keeps no output. + pub run_output: Option<(crate::run_output::models::OutputStore, u16)>, } /// One pooled outbound connection; the location never receives a store handle. @@ -61,6 +65,11 @@ pub enum LocationHealth { /// Every provider missing a secret, including those the target allows; names only, never values. providers: Vec, }, + /// The discovered sets a publication used; a failed set keeps serving its last good items. + Discovery { + generation: i64, + sets: Vec, + }, /// Jobs and groups this server's `pool_caps` clamp, derived by the server, never reported by a location. PoolCapped { generation: i64, @@ -104,6 +113,8 @@ pub struct PublishedGeneration { pub state_locations: Vec, /// The providers whose required secrets the location's environment leaves unset. pub missing_secrets: Vec, + /// For each provider missing secrets, the node keys that use it and then those that read them. + pub secrets_needed_by: BTreeMap>, } /// A provider whose required secrets are unset: what is missing and which nodes need it, never a value. @@ -129,6 +140,21 @@ pub struct MissingProviderSetting { pub line: Option, } +/// One discovered set as a location's health names it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct DiscoveryHealth { + pub name: String, + pub status: DiscoveredSetStatus, + /// Why the newest attempt failed, secrets masked. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + /// How many items the set serves: its newest result, or the last good one after a failure. + pub items: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_good_at: Option>, +} + /// The stage a warehouse sync failed at; only a failed read also reports its redacted error. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "snake_case")] @@ -174,12 +200,14 @@ pub enum LocationState { FallingBack, /// A provider secret is unset in the location's environment, so runs that use the provider fail. MissingSecrets, + /// A discover function failed at the last publication, so its set serves its last good items or none. + DiscoveryFailed, /// No instance has checked in for 90 seconds. Broken, } impl LocationState { - /// `target`'s state at `now` from observations that may cover several targets: down without a recent check-in, then a failed load, then missing provider secrets, then a failed connection. + /// `target`'s state at `now` from observations that may cover several targets: down without a recent check-in, then a failed load, then missing provider secrets, then a failed discover function, then a failed connection. #[must_use] pub fn of( observations: &[LocationHealthObservation], @@ -200,6 +228,7 @@ impl LocationState { let mut failed: Option<(DateTime, i64)> = None; let mut connection: Option<(DateTime, i64, bool)> = None; let mut secrets: Option<(DateTime, u64)> = None; + let mut discovery: Option<(DateTime, bool)> = None; for observation in own { let seen = observation.received_at; match observation.report.health { @@ -220,6 +249,14 @@ impl LocationState { { secrets = Some((seen, missing)); } + LocationHealth::Discovery { ref sets, .. } + if discovery.is_none_or(|(at, _)| seen > at) => + { + let failing: bool = sets + .iter() + .any(|set| set.status == DiscoveredSetStatus::Failed); + discovery = Some((seen, failing)); + } _ => {} } } @@ -229,6 +266,7 @@ impl LocationState { } (Some(_), None, _) => Self::FallingBack, (_, _, Some((_, missing))) if missing > 0 => Self::MissingSecrets, + _ if discovery.is_some_and(|(_, failing)| failing) => Self::DiscoveryFailed, (_, Some((_, _, false)), _) => Self::Degraded, _ => Self::Healthy, } @@ -261,6 +299,11 @@ pub enum LocationWork { #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")] given: std::collections::BTreeSet, }, + /// Compile and publish again, calling every discover function, as `r` does in `sqb dev`. + Republish { + /// The name of whoever asked, which the location prints with the request's reason. + requested_by: String, + }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] @@ -296,6 +339,29 @@ pub struct PersonWorkRequest { pub struct LocationWorkPoll { pub session_id: Uuid, pub target: String, + /// Which work this poll takes. + pub scope: LocationWorkScope, +} + +/// Which work a location takes in one poll. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum LocationWorkScope { + /// Every kind of work, while the location serves a publication of its current files. + All, + /// Only republishes, while the location has no publication of its current files. + RepublishOnly, +} + +impl LocationWorkScope { + /// The scope's name as the claim query compares it. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::All => "all", + Self::RepublishOnly => "republish_only", + } + } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] @@ -327,6 +393,16 @@ pub enum LocationWorkOutcome { }, /// The location took the request; its next metadata sync reads the warehouse. SyncStarted {}, + /// The republish published this snapshot. + Published { + snapshot_id: Uuid, + generation: i64, + }, + /// The republish compiled nothing to publish; the last good snapshot keeps serving. + PublishFailed { + generation: i64, + error: String, + }, Superseded {}, } @@ -928,3 +1004,73 @@ pub struct PlanTimingStep { pub name: String, pub seconds: f64, } + +/// Where a republish request stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum RepublishState { + /// Waiting for the location to take it, or to finish publishing. + Pending, + Published, + Failed, + /// No location took it before it expired. + Expired, +} + +/// A republish request and its result once the location has one. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct RepublishStatus { + pub request_id: Uuid, + pub location_id: Uuid, + pub target: String, + pub state: RepublishState, + pub requested_by: String, + pub reason: String, + pub requested_at: DateTime, + pub expires_at: DateTime, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completed_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub snapshot_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub generation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// One discovered set of the current snapshot, as a deploy reads it back. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct DiscoveredSetReadback { + pub name: String, + pub status: DiscoveredSetStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fetched_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_good_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub digest: Option, + /// The tags of the result the set serves: its newest, or its last good one after a failure. + #[schema(value_type = Object)] + pub tags: std::collections::BTreeMap, + pub items: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub check_every_seconds: Option, +} + +/// The discovered sets of a target's current snapshot; empty when it saved none. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct DiscoveredReadback { + pub snapshot_id: Uuid, + pub generation: i64, + pub published_at: DateTime, + pub sets: Vec, +} + +/// What a republish client sends: a new request, or a read of one that holds open while it is pending. +#[derive(Clone, Copy, Debug)] +pub enum RepublishCall<'a> { + Request(&'a PersonWorkRequest), + Read { request_id: Uuid, wait: u64 }, +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/chunks.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/chunks.rs new file mode 100644 index 0000000000..aebb688ff9 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/chunks.rs @@ -0,0 +1,87 @@ +//! A chunk's text: its lines, which of them look like errors or warnings, how lines fold, and its zstd form. + +use crate::run_output::constants::{MARK_TEXT_BYTES, ZSTD_LEVEL}; +use crate::run_output::models::OutputLevel; +use crate::store::errors::ControlError; + +const ERROR_WORDS: [&str; 4] = ["error", "exception", "traceback", "fatal"]; +const WARNING_WORDS: [&str; 1] = ["warn"]; + +/// How many lines `text` holds; every line ends in a newline. +pub(crate) fn line_count(text: &str) -> i64 { + i64::try_from(text.bytes().filter(|byte| *byte == b'\n').count()).unwrap_or(i64::MAX) +} + +/// The lines of `text`, without their newlines. +pub(crate) fn lines(text: &str) -> Vec<&str> { + text.split_terminator('\n').collect() +} + +/// Whether `line` reads as an error or a warning; error words win. +pub(crate) fn level_of(line: &str) -> Option { + let lower: String = line.to_lowercase(); + if ERROR_WORDS.iter().any(|word| lower.contains(word)) { + Some(OutputLevel::Error) + } else if WARNING_WORDS.iter().any(|word| lower.contains(word)) { + Some(OutputLevel::Warning) + } else { + None + } +} + +/// The first `room` of `text`'s lines that read as errors or warnings: each one's offset within `text`, level and text. +pub(crate) fn marked_lines(text: &str, room: usize) -> Vec<(i64, OutputLevel, String)> { + let mut marks: Vec<(i64, OutputLevel, String)> = Vec::new(); + for (offset, line) in (0_i64..).zip(lines(text)) { + if marks.len() == room { + break; + } + if let Some(level) = level_of(line) { + marks.push((offset, level, mark_text(line))); + } + } + marks +} + +/// `line` cut to a mark's limit at a character boundary, without NUL, which PostgreSQL text can't hold; the chunk keeps it. +fn mark_text(line: &str) -> String { + let end: usize = (0..=line.len().min(MARK_TEXT_BYTES)) + .rev() + .find(|index| line.is_char_boundary(*index)) + .unwrap_or(0); + line[..end].replace('\0', "") +} + +/// What lines that are the same but for their numbers share: the line with each run of digits replaced by one `#`. +pub(crate) fn similar_key(line: &str) -> String { + let mut key: String = String::with_capacity(line.len()); + let mut in_digits: bool = false; + for character in line.chars() { + if character.is_ascii_digit() { + if !in_digits { + key.push('#'); + } + in_digits = true; + } else { + key.push(character); + in_digits = false; + } + } + key +} + +pub(crate) fn compress(text: &[u8]) -> Result, ControlError> { + Ok(zstd::bulk::compress(text, ZSTD_LEVEL)?) +} + +/// The text of a chunk, which is at most `capacity` bytes once decompressed. +pub(crate) fn decompress(stored: &[u8], capacity: usize) -> Result { + let bytes: Vec = zstd::bulk::decompress(stored, capacity)?; + String::from_utf8(bytes) + .map_err(|error| ControlError::Invalid(format!("run output chunk: {error}"))) +} + +/// Whether a count is zero, so a line with nothing left out before it serializes without the field. +pub(crate) const fn is_zero(value: &i64) -> bool { + *value == 0 +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/folders.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/folders.rs new file mode 100644 index 0000000000..6f3a03c95c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/folders.rs @@ -0,0 +1,38 @@ +//! Where run output goes when `[output] store` names nowhere. + +use std::path::PathBuf; + +use crate::run_output::constants::{ + DEFAULT_OUTPUT_FOLDER, HOME_STATE_FOLDER, NO_STATE_HOME, STATE_HOME_VARIABLE, STATE_SUBFOLDER, +}; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; + +/// `XDG_STATE_HOME`, then the user's home: `HOME` (`USERPROFILE` on Windows), else the account's own. +pub(crate) fn user_folders() -> (Option, Option) { + ( + std::env::var_os(STATE_HOME_VARIABLE).map(PathBuf::from), + std::env::home_dir(), + ) +} + +/// `output` beside a SQLite control store; for PostgreSQL in the user's state folder, wherever the server started. +pub(crate) fn default_folder( + control: &ControlStore, + (state_home, home): (Option, Option), +) -> Result { + match control { + ControlStore::Sqlite(sqlite) => Ok(sqlite.path.parent().map_or_else( + || PathBuf::from(DEFAULT_OUTPUT_FOLDER), + |folder| folder.join(DEFAULT_OUTPUT_FOLDER), + )), + ControlStore::Postgres(_) => state_home + .filter(|folder| folder.is_absolute()) + .or_else(|| { + home.filter(|folder| folder.is_absolute()) + .map(|folder| folder.join(HOME_STATE_FOLDER)) + }) + .map(|state| state.join(STATE_SUBFOLDER).join(DEFAULT_OUTPUT_FOLDER)) + .ok_or_else(|| ControlError::Invalid(NO_STATE_HOME.into())), + } +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs new file mode 100644 index 0000000000..aa752a0eb7 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs @@ -0,0 +1,193 @@ +//! The control store's index of a run's output: chunks, segments, stream totals and what a cap dropped. + +use uuid::Uuid; + +use crate::run_output::constants::{HEAD_PART, MARKED_LINES, TAIL_PART}; +use crate::run_output::models::{ + PreparedChunk, PreparedSegment, StoredNodeLines, StoredTotals, TailChunk, +}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::main::query_records::query_records; +use crate::store::models::{Change, ControlTransaction, Parameter}; + +/// Whether this claim already stored `batch`. +pub(crate) async fn batch_stored( + transaction: ControlTransaction, + (run_id, claim_id): (Uuid, Uuid), + batch: u64, +) -> Result<(ControlTransaction, bool), ControlError> { + let (transaction, rows) = query( + transaction, + "SELECT chunk FROM sqb_run_output_chunks WHERE run_id=$1 AND claim_id=$2 AND batch=$3", + vec![ + Parameter::Id(run_id), + Parameter::Id(claim_id), + Parameter::Integer(integer(batch)?), + ], + ) + .await?; + Ok((transaction, !rows.is_empty())) +} + +/// Index one chunk, numbering each segment's lines after the run's last and after its node's last; past `half` of a capped run's bytes the oldest later chunks go, and their object keys come back for deletion. +pub(crate) async fn record_chunk( + transaction: ControlTransaction, + chunk: &PreparedChunk, + half: Option, +) -> Result<(ControlTransaction, Vec), ControlError> { + let (mut transaction, totals) = totals(transaction, chunk.run_id).await?; + let StoredTotals { + next_chunk: number, + line_count: mut run_lines, + head_bytes: head, + tail_bytes: tail, + } = totals; + let received_at = transaction.now; + let part: &str = match half { + Some(half) if tail > 0 || head + chunk.text_bytes > half => TAIL_PART, + _ => HEAD_PART, + }; + (transaction, _) = query(transaction, + "INSERT INTO sqb_run_output_chunks (run_id, chunk, claim_id, batch, object_key, text_bytes, received_at, part) \ + VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", + vec![Parameter::Id(chunk.run_id), Parameter::Integer(number), Parameter::Id(chunk.claim_id), + Parameter::Integer(integer(chunk.batch)?), Parameter::Text(chunk.object_key.clone()), + Parameter::Integer(chunk.text_bytes), Parameter::Time(received_at), Parameter::Text(part.into())]).await?; + (transaction, _) = query(transaction, + "UPDATE sqb_run_output SET next_chunk=next_chunk+1, head_bytes=head_bytes+$2, tail_bytes=tail_bytes+$3, \ + stored_bytes=stored_bytes+$4, dropped_bytes=dropped_bytes+$5 WHERE run_id=$1", + vec![Parameter::Id(chunk.run_id), + Parameter::Integer(if part == HEAD_PART { chunk.text_bytes } else { 0 }), + Parameter::Integer(if part == TAIL_PART { chunk.text_bytes } else { 0 }), + Parameter::Integer(chunk.stored_bytes), Parameter::Integer(chunk.dropped_bytes)]).await?; + for segment in &chunk.segments { + transaction = + record_segment(transaction, (chunk.run_id, number, run_lines + 1), segment).await?; + run_lines += segment.line_count; + } + (transaction, _) = query( + transaction, + "UPDATE sqb_run_output SET line_count=$2 WHERE run_id=$1", + vec![Parameter::Id(chunk.run_id), Parameter::Integer(run_lines)], + ) + .await?; + transaction.changes.insert(Change::Run(chunk.run_id)); + match half { + Some(half) if part == TAIL_PART => { + drop_oldest_tail(transaction, (chunk.run_id, number), half).await + } + _ => Ok((transaction, Vec::new())), + } +} + +/// Start the run's totals once, and read them. +async fn totals( + transaction: ControlTransaction, + run_id: Uuid, +) -> Result<(ControlTransaction, StoredTotals), ControlError> { + let (transaction, _) = query(transaction, + "INSERT INTO sqb_run_output (run_id, next_chunk, line_count, head_bytes, tail_bytes, stored_bytes, omitted_bytes, omitted_lines, dropped_bytes) \ + VALUES ($1,0,0,0,0,0,0,0,0) ON CONFLICT (run_id) DO NOTHING", + vec![Parameter::Id(run_id)]).await?; + let (transaction, rows): (ControlTransaction, Vec) = query_records( + transaction, + "SELECT next_chunk, line_count, head_bytes, tail_bytes FROM sqb_run_output WHERE run_id=$1", + vec![Parameter::Id(run_id)], + ) + .await?; + let found: StoredTotals = rows + .into_iter() + .next() + .ok_or_else(|| ControlError::Invalid("run output totals are missing".into()))?; + Ok((transaction, found)) +} + +async fn record_segment( + transaction: ControlTransaction, + (run_id, chunk, run_line): (Uuid, i64, i64), + segment: &PreparedSegment, +) -> Result { + let stream: &str = segment.stream.as_str(); + let node: Parameter = Parameter::Text(segment.node_key.clone()); + let (transaction, rows): (ControlTransaction, Vec) = query_records(transaction, + "SELECT CAST(COALESCE(SUM(line_count), 0) AS BIGINT) AS node_lines, \ + CAST(COALESCE(SUM(CASE WHEN stream=$3 THEN mark_count ELSE 0 END), 0) AS BIGINT) AS stream_marks \ + FROM sqb_run_output_streams WHERE run_id=$1 AND node_key=$2", + vec![Parameter::Id(run_id), node.clone(), Parameter::Text(stream.into())]).await?; + let before: StoredNodeLines = rows.into_iter().next().unwrap_or_default(); + let node_line: i64 = before.node_lines + 1; + let (mut transaction, _) = query(transaction, + "INSERT INTO sqb_run_output_segments (run_id, chunk, node_key, stream, run_line, node_line, line_count, text_offset, text_bytes) \ + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", + vec![Parameter::Id(run_id), Parameter::Integer(chunk), node.clone(), Parameter::Text(stream.into()), + Parameter::Integer(run_line), Parameter::Integer(node_line), Parameter::Integer(segment.line_count), + Parameter::Integer(segment.text_offset), Parameter::Integer(segment.text_bytes)]).await?; + let room: usize = + MARKED_LINES.saturating_sub(usize::try_from(before.stream_marks).unwrap_or(MARKED_LINES)); + let marks = &segment.marks[..segment.marks.len().min(room)]; + for (offset, level, text) in marks { + (transaction, _) = query(transaction, + "INSERT INTO sqb_run_output_marks (run_id, node_key, node_line, stream, level, text) VALUES ($1,$2,$3,$4,$5,$6)", + vec![Parameter::Id(run_id), node.clone(), Parameter::Integer(node_line + offset), + Parameter::Text(stream.into()), Parameter::Text(level.as_str().into()), Parameter::Text(text.clone())]).await?; + } + let (transaction, _) = query(transaction, + "INSERT INTO sqb_run_output_streams (run_id, node_key, stream, line_count, text_bytes, mark_count) \ + VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (run_id, node_key, stream) DO UPDATE SET \ + line_count=sqb_run_output_streams.line_count+$4, text_bytes=sqb_run_output_streams.text_bytes+$5, \ + mark_count=sqb_run_output_streams.mark_count+$6", + vec![Parameter::Id(run_id), node, Parameter::Text(stream.into()), + Parameter::Integer(segment.line_count), Parameter::Integer(segment.text_bytes), + Parameter::Integer(i64::try_from(marks.len()).unwrap_or(i64::MAX))]).await?; + Ok(transaction) +} + +/// Drop the oldest later chunks, never the newest, until the run's last part fits in `half`. +async fn drop_oldest_tail( + mut transaction: ControlTransaction, + (run_id, newest): (Uuid, i64), + half: i64, +) -> Result<(ControlTransaction, Vec), ControlError> { + let mut dropped: Vec = Vec::new(); + loop { + let rows: Vec; + (transaction, rows) = query_records(transaction, + "SELECT c.chunk, c.text_bytes, c.object_key, CAST(COALESCE((SELECT SUM(s.line_count) FROM sqb_run_output_segments s \ + WHERE s.run_id=c.run_id AND s.chunk=c.chunk), 0) AS BIGINT) AS lines FROM sqb_run_output_chunks c JOIN sqb_run_output o ON o.run_id=c.run_id \ + WHERE c.run_id=$1 AND c.part='tail' AND c.chunk<$2 AND o.tail_bytes>$3 ORDER BY c.chunk LIMIT 1", + vec![Parameter::Id(run_id), Parameter::Integer(newest), Parameter::Integer(half)]).await?; + let Some(TailChunk { + chunk, + text_bytes: bytes, + object_key: key, + lines, + }) = rows.into_iter().next() + else { + return Ok((transaction, dropped)); + }; + for sql in [ + "DELETE FROM sqb_run_output_marks WHERE run_id=$1 AND EXISTS (SELECT 1 FROM sqb_run_output_segments s \ + WHERE s.run_id=$1 AND s.chunk=$2 AND s.node_key=sqb_run_output_marks.node_key \ + AND sqb_run_output_marks.node_line>=s.node_line AND sqb_run_output_marks.node_line Result { + i64::try_from(value) + .map_err(|_| ControlError::Invalid("run output counter is out of range".into())) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/lines.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/lines.rs new file mode 100644 index 0000000000..28b5015811 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/lines.rs @@ -0,0 +1,133 @@ +//! A view's lines in order, forwards or backwards, read a batch of segments at a time. + +use std::sync::Arc; + +use crate::run_output::_helpers::chunks::{level_of, lines}; +use crate::run_output::_helpers::objects::read_chunk; +use crate::run_output::_helpers::views::{view_gap, view_segments}; +use crate::run_output::constants::SEGMENT_BATCH; +use crate::run_output::models::{ + OutputLine, OutputStore, OutputView, SearchDirection, StoredSegment, ViewReader, +}; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit}; +use crate::store::models::{ControlStore, TransactionMode}; + +impl<'a> ViewReader<'a> { + /// Read `view` from `bound`: forwards from that line, or backwards from just before it. + pub(crate) async fn open( + (store, output): (&'a ControlStore, &'a OutputStore), + view: &'a OutputView, + (direction, bound): (SearchDirection, i64), + ) -> Result { + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, gap) = view_gap(transaction, view).await?; + commit(transaction).await?; + Ok(Self { + store, + output, + view, + direction, + bound, + gap, + pending: std::collections::VecDeque::new(), + exhausted: false, + cached: None, + chunks_read: 0, + }) + } + + /// The next line in the reader's direction, or `None` past the view's end. + pub(crate) async fn next_line(&mut self) -> Result, ControlError> { + while self.pending.is_empty() && !self.exhausted { + self.fill().await?; + } + Ok(self.pending.pop_front()) + } + + async fn fill(&mut self) -> Result<(), ControlError> { + let transaction = begin(self.store, TransactionMode::Read).await?; + let (transaction, segments) = view_segments( + transaction, + self.view, + (self.direction, self.bound), + SEGMENT_BATCH, + ) + .await?; + commit(transaction).await?; + self.exhausted = segments.is_empty(); + for segment in segments { + let chunk: Arc = self.chunk(&segment).await?; + let found: Vec = self.segment_lines(&chunk, &segment)?; + self.pending.extend(found); + self.bound = match self.direction { + SearchDirection::Forward => segment.first_line + segment.line_count, + SearchDirection::Backward => segment.first_line, + }; + } + Ok(()) + } + + /// The segment's lines on the reader's side of its bound, in the reader's direction. + fn segment_lines( + &self, + chunk: &str, + segment: &StoredSegment, + ) -> Result, ControlError> { + let mut found: Vec = Vec::new(); + for (number, text) in (segment.first_line..).zip(lines(segment_text(chunk, segment)?)) { + let wanted: bool = match self.direction { + SearchDirection::Forward => number >= self.bound, + SearchDirection::Backward => number < self.bound, + }; + if !wanted { + continue; + } + found.push(OutputLine { + number, + node_key: segment.node_key.clone(), + stream: segment.stream, + at: segment.received_at, + level: level_of(text), + text: text.to_owned(), + omitted_before: match self.gap { + Some((first, left_out)) if first == number => left_out, + _ => 0, + }, + }); + } + if self.direction == SearchDirection::Backward { + found.reverse(); + } + Ok(found) + } + + /// The text of the segment's chunk, read once while consecutive segments share it. + async fn chunk(&mut self, segment: &StoredSegment) -> Result, ControlError> { + if let Some((key, text)) = &self.cached + && *key == segment.object_key + { + return Ok(Arc::clone(text)); + } + let capacity: usize = usize::try_from(segment.chunk_text_bytes).map_err(|_| invalid())?; + let text: Arc = + Arc::new(read_chunk(self.output, &segment.object_key, capacity).await?); + self.cached = Some((segment.object_key.clone(), Arc::clone(&text))); + self.chunks_read += 1; + Ok(text) + } +} + +/// The text of one segment within its chunk's text. +pub(crate) fn segment_text<'a>( + chunk: &'a str, + segment: &StoredSegment, +) -> Result<&'a str, ControlError> { + let start: usize = usize::try_from(segment.text_offset).map_err(|_| invalid())?; + let end: usize = start + usize::try_from(segment.text_bytes).map_err(|_| invalid())?; + chunk.get(start..end).ok_or_else(invalid) +} + +pub(crate) fn invalid() -> ControlError { + ControlError::Invalid("run output index points outside its chunk".into()) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/mod.rs new file mode 100644 index 0000000000..1deb3d6e6b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/mod.rs @@ -0,0 +1,10 @@ +pub(crate) mod chunks; +pub(crate) mod folders; +pub(crate) mod index; +pub(crate) mod lines; +pub(crate) mod objects; +pub(crate) mod pages; +pub(crate) mod prepare; +pub(crate) mod prune; +pub(crate) mod upload; +pub(crate) mod views; diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/objects.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/objects.rs new file mode 100644 index 0000000000..ecf461fe8a --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/objects.rs @@ -0,0 +1,55 @@ +//! Chunks in the output store, keyed by run, claim and batch. + +use object_store::ObjectStoreExt; +use object_store::path::Path; +use uuid::Uuid; + +use crate::run_output::_helpers::chunks::decompress; +use crate::run_output::models::OutputStore; +use crate::store::errors::ControlError; + +/// The key of one batch's chunk; a retried batch writes the same object again. +pub(crate) fn chunk_key(store: &OutputStore, (run_id, claim_id): (Uuid, Uuid), batch: u64) -> Path { + run_prefix(store, run_id) + .join(claim_id.to_string()) + .join(format!("{batch:012}.zst")) +} + +/// Every object of one run sits under this prefix. +pub(crate) fn run_prefix(store: &OutputStore, run_id: Uuid) -> Path { + store.prefix.clone().join("runs").join(run_id.to_string()) +} + +pub(crate) async fn put_chunk( + store: &OutputStore, + key: &Path, + stored: Vec, +) -> Result<(), ControlError> { + store.objects.put(key, stored.into()).await?; + Ok(()) +} + +/// A chunk's text, at most `capacity` bytes. +pub(crate) async fn read_chunk( + store: &OutputStore, + key: &str, + capacity: usize, +) -> Result { + let stored = store.objects.get(&Path::from(key)).await?.bytes().await?; + let text: String = tokio::task::spawn_blocking(move || decompress(&stored, capacity)).await??; + Ok(text) +} + +/// Delete chunks; one already gone is not an error. +pub(crate) async fn delete_chunks( + store: &OutputStore, + keys: &[String], +) -> Result<(), ControlError> { + for key in keys { + match store.objects.delete(&Path::from(key.as_str())).await { + Ok(()) | Err(object_store::Error::NotFound { .. }) => {} + Err(error) => return Err(error.into()), + } + } + Ok(()) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/pages.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/pages.rs new file mode 100644 index 0000000000..598f68dbb8 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/pages.rs @@ -0,0 +1,254 @@ +//! Pages of a view's lines with similar lines folded, searches from a line in either direction, and a view's whole text. + +use crate::run_output::_helpers::chunks::similar_key; +use crate::run_output::_helpers::lines::segment_text; +use crate::run_output::_helpers::objects::read_chunk; +use crate::run_output::_helpers::views::view_segments; +use crate::run_output::constants::{ + AROUND_OPEN_LINES, COLLAPSE_SCAN_LINES, MIN_SIMILAR_LINES, SEARCH_CHUNKS, SEGMENT_BATCH, +}; +use crate::run_output::models::{ + OutputLine, OutputPageQuery, OutputRow, OutputSearch, OutputStore, OutputView, PageRows, + SearchDirection, SearchTally, SimilarRun, ViewReader, +}; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit}; +use crate::store::models::{ControlStore, TransactionMode}; + +/// Up to `limit` rows in the reader's direction, in line order; with `collapse`, runs of similar lines fold, and a run may be read past the last row to its end. +pub(crate) async fn page_rows( + reader: &mut ViewReader<'_>, + limit: usize, + (collapse, around): (bool, Option), +) -> Result { + let mut page = PageRows::default(); + let mut run = SimilarRun::default(); + let mut scanned_past: i64 = 0; + while page.rows.len() < limit || !run.lines.is_empty() { + if page.rows.len() >= limit { + scanned_past += 1; + if scanned_past > COLLAPSE_SCAN_LINES { + break; + } + } + let Some(line) = reader.next_line().await? else { + break; + }; + let open: bool = around.is_some_and(|at| (line.number - at).abs() <= AROUND_OPEN_LINES); + if !collapse || open { + page.flush(std::mem::take(&mut run)); + if page.rows.len() >= limit { + break; + } + page.push_line(line); + continue; + } + let key: String = similar_key(&line.text); + if run.key.as_deref() != Some(key.as_str()) { + page.flush(std::mem::take(&mut run)); + if page.rows.len() >= limit { + break; + } + run.key = Some(key); + } + run.lines.push(line); + } + page.flush(std::mem::take(&mut run)); + if reader.direction == SearchDirection::Backward { + page.rows.reverse(); + } + Ok(page) +} + +impl SearchTally { + /// Count a match at `number`, a search from `from` being where it was asked to look. + fn count(&mut self, number: i64, from: i64) { + self.count += 1; + self.first = self.first.or(Some(number)); + self.last = Some(number); + self.before += i64::from(number < from); + if number <= from { + self.through += 1; + self.upto = Some(number); + } + if number >= from && self.after.is_none() { + self.after = Some(number); + } + } +} + +impl PageRows { + fn push_line(&mut self, line: OutputLine) { + self.cover((line.number, line.number)); + self.rows.push(OutputRow::Line { line }); + } + + fn cover(&mut self, (low, high): (i64, i64)) { + self.low = Some(self.low.map_or(low, |seen| seen.min(low))); + self.high = Some(self.high.map_or(high, |seen| seen.max(high))); + } + + /// Add a run of similar lines: one folded row when it is long enough, else each line. + fn flush(&mut self, run: SimilarRun) { + let lines: Vec = run.lines; + if lines.len() < MIN_SIMILAR_LINES { + for line in lines { + self.push_line(line); + } + return; + } + let low: i64 = lines + .iter() + .map(|line| line.number) + .min() + .unwrap_or_default(); + let high: i64 = lines + .iter() + .map(|line| line.number) + .max() + .unwrap_or_default(); + let sample: OutputLine = lines + .iter() + .find(|line| line.number == low) + .cloned() + .unwrap_or_else(|| lines[0].clone()); + self.cover((low, high)); + self.rows.push(OutputRow::Similar { + from: low, + count: i64::try_from(lines.len()).unwrap_or(i64::MAX), + sample, + }); + } +} + +/// Search a small view whole: the match nearest `from` in `direction`, wrapping round, with the count and its rank. +pub(crate) async fn search_whole( + reader: &mut ViewReader<'_>, + needle: &str, + (from, direction): (i64, SearchDirection), +) -> Result { + let mut tally = SearchTally::default(); + while let Some(line) = reader.next_line().await? { + if line.text.to_lowercase().contains(needle) { + tally.count(line.number, from); + } + } + let count: i64 = tally.count; + let (line, rank) = match direction { + SearchDirection::Forward => tally + .after + .map_or((tally.first, 1), |found| (Some(found), tally.before + 1)), + SearchDirection::Backward => tally + .upto + .map_or((tally.last, count), |found| (Some(found), tally.through)), + }; + Ok(OutputSearch { + line, + count: Some(count), + rank: line.map(|_| rank), + continue_from: None, + }) +} + +/// Search a large view from the reader's bound, at most `SEARCH_CHUNKS` chunks: the first match, or where to continue. +pub(crate) async fn search_part( + reader: &mut ViewReader<'_>, + needle: &str, +) -> Result { + let mut scanned: Option = None; + while reader.chunks_read <= SEARCH_CHUNKS { + let Some(line) = reader.next_line().await? else { + return Ok(OutputSearch { + line: None, + count: None, + rank: None, + continue_from: None, + }); + }; + if line.text.to_lowercase().contains(needle) { + return Ok(OutputSearch { + line: Some(line.number), + count: None, + rank: None, + continue_from: None, + }); + } + scanned = Some(line.number); + } + Ok(OutputSearch { + line: None, + count: None, + rank: None, + continue_from: scanned.map(|number| match reader.direction { + SearchDirection::Forward => number + 1, + SearchDirection::Backward => number - 1, + }), + }) +} + +/// The view's text from `bound` on, one batch of segments, and where the next batch starts; `None` past the end. +pub(crate) async fn text_after( + (store, output): (&ControlStore, &OutputStore), + view: &OutputView, + bound: i64, +) -> Result, ControlError> { + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, segments) = view_segments( + transaction, + view, + (SearchDirection::Forward, bound), + SEGMENT_BATCH, + ) + .await?; + commit(transaction).await?; + let Some(last) = segments.last() else { + return Ok(None); + }; + let next: i64 = last.first_line + last.line_count; + let mut text: String = String::new(); + for segment in &segments { + let capacity: usize = usize::try_from(segment.chunk_text_bytes).unwrap_or(usize::MAX); + let chunk: String = read_chunk(output, &segment.object_key, capacity).await?; + text.push_str(segment_text(&chunk, segment)?); + } + Ok(Some((text, next))) +} + +/// Where a page reads from: backwards from the end for `tail`, backwards from `before`, or forwards from `from`; giving more than one is refused. +pub(crate) fn page_start( + query: &OutputPageQuery, + line_count: i64, +) -> Result<(SearchDirection, i64), ControlError> { + let named: usize = [query.from.is_some(), query.before.is_some(), query.tail] + .into_iter() + .filter(|named| *named) + .count(); + if named > 1 { + return Err(ControlError::Invalid( + "read a page from one place: from, before or tail".into(), + )); + } + Ok(match (query.tail, query.before) { + (true, _) => (SearchDirection::Backward, line_count + 1), + (false, Some(before)) => (SearchDirection::Backward, before), + (false, None) => (SearchDirection::Forward, query.from.unwrap_or(1).max(1)), + }) +} + +/// `from` for the page after lines `from`..`to`, and `before` for the page before them, where the view has such lines. +pub(crate) async fn page_neighbours( + store: &ControlStore, + view: &OutputView, + (from, to): (i64, i64), +) -> Result<(Option, Option), ControlError> { + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, later) = + view_segments(transaction, view, (SearchDirection::Forward, to), 1).await?; + let (transaction, earlier) = + view_segments(transaction, view, (SearchDirection::Backward, from), 1).await?; + commit(transaction).await?; + Ok(( + (!later.is_empty()).then_some(to), + (!earlier.is_empty()).then_some(from), + )) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/prepare.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/prepare.rs new file mode 100644 index 0000000000..7c5f259b51 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/prepare.rs @@ -0,0 +1,86 @@ +//! A worker batch checked and laid out as one chunk: its text, zstd form and each segment's place. + +use uuid::Uuid; + +use crate::run_output::_helpers::chunks::{compress, line_count, marked_lines}; +use crate::run_output::constants::{ + MARKED_LINES, MAX_BATCH_SEGMENTS, MAX_BATCH_TEXT_BYTES, RUN_OUTPUT_NODE, +}; +use crate::run_output::models::{OutputBatch, PreparedChunk, PreparedSegment}; +use crate::store::errors::ControlError; + +/// Refuse a batch past its limits, a segment that is empty or ends mid-line, and a node key that is not `:`. +pub(crate) fn checked(batch: &OutputBatch) -> Result<(), ControlError> { + let bytes: usize = batch + .segments + .iter() + .map(|segment| segment.text.len()) + .sum(); + if batch.segments.len() > MAX_BATCH_SEGMENTS || bytes > MAX_BATCH_TEXT_BYTES { + return Err(ControlError::Invalid( + "run output batch exceeds its limit".into(), + )); + } + for segment in &batch.segments { + if !segment.text.ends_with('\n') { + return Err(ControlError::Invalid( + "run output segments hold complete lines".into(), + )); + } + if segment.node_key.as_deref().is_some_and(|key| { + !key.split_once(':') + .is_some_and(|(kind, name)| !kind.is_empty() && !name.is_empty()) + }) { + return Err(ControlError::Invalid( + "run output node keys are :".into(), + )); + } + } + Ok(()) +} + +/// The chunk of `batch` and its zstd form, written under `object_key`. +pub(crate) fn prepared( + (run_id, claim_id): (Uuid, Uuid), + batch: &OutputBatch, + object_key: String, +) -> Result<(PreparedChunk, Vec), ControlError> { + let mut text: String = String::new(); + let mut segments: Vec = Vec::with_capacity(batch.segments.len()); + let mut dropped: u64 = 0; + for segment in &batch.segments { + let marks = marked_lines(&segment.text, MARKED_LINES); + segments.push(PreparedSegment { + node_key: segment + .node_key + .clone() + .unwrap_or_else(|| RUN_OUTPUT_NODE.into()), + stream: segment.stream, + line_count: line_count(&segment.text), + text_offset: counter(text.len())?, + text_bytes: counter(segment.text.len())?, + marks, + }); + dropped = dropped.saturating_add(segment.dropped_bytes); + text.push_str(&segment.text); + } + let stored: Vec = compress(text.as_bytes())?; + Ok(( + PreparedChunk { + run_id, + claim_id, + batch: batch.batch, + object_key, + text_bytes: counter(text.len())?, + stored_bytes: counter(stored.len())?, + dropped_bytes: i64::try_from(dropped).unwrap_or(i64::MAX), + segments, + }, + stored, + )) +} + +fn counter(value: usize) -> Result { + i64::try_from(value) + .map_err(|_| ControlError::Invalid("run output counter is out of range".into())) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/prune.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/prune.rs new file mode 100644 index 0000000000..b7157c1dc1 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/prune.rs @@ -0,0 +1,87 @@ +//! Removing one run's output so the index never points at a missing object. + +use chrono::TimeDelta; +use futures_util::StreamExt; +use object_store::ObjectStoreExt; +use uuid::Uuid; + +use crate::run_output::_helpers::objects::run_prefix; +use crate::run_output::constants::PRUNE_RUNS; +use crate::run_output::models::{ExpiredRun, OutputStore}; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::main::query_records::query_records; +use crate::store::main::write::write; +use crate::store::models::{ControlStore, Parameter}; + +/// Index first (all but the `sqb_run_output` row), then objects, then that row, so a failure is retried and nothing points at a deleted object. +pub(crate) async fn prune_run( + store: &ControlStore, + output: &OutputStore, + run_id: Uuid, +) -> Result<(), ControlError> { + delete_index( + store, + run_id, + &[ + "DELETE FROM sqb_run_output_marks WHERE run_id=$1", + "DELETE FROM sqb_run_output_segments WHERE run_id=$1", + "DELETE FROM sqb_run_output_chunks WHERE run_id=$1", + "DELETE FROM sqb_run_output_streams WHERE run_id=$1", + ], + ) + .await?; + let prefix = run_prefix(output, run_id); + let mut listed = output.objects.list(Some(&prefix)); + while let Some(object) = listed.next().await { + output.objects.delete(&object?.location).await?; + } + delete_index( + store, + run_id, + &["DELETE FROM sqb_run_output WHERE run_id=$1"], + ) + .await +} + +async fn delete_index( + store: &ControlStore, + run_id: Uuid, + statements: &[&str], +) -> Result<(), ControlError> { + write(store, |mut transaction| async move { + for sql in statements { + (transaction, _) = query(transaction, sql, vec![Parameter::Id(run_id)]).await?; + } + Ok((transaction, ())) + }) + .await +} + +/// Runs that ended more than `days` ago and still have output, oldest first. +pub(crate) async fn expired_runs( + store: &ControlStore, + days: u16, +) -> Result, ControlError> { + write(store, |transaction| async move { + let cutoff = transaction.now - TimeDelta::days(i64::from(days)); + query_records( + transaction, + "SELECT o.run_id FROM sqb_run_output o JOIN sqb_runs r ON r.run_id=o.run_id \ + WHERE r.ended_at IS NOT NULL AND r.ended_at<$1 ORDER BY r.ended_at LIMIT $2", + vec![Parameter::Time(cutoff), Parameter::Integer(PRUNE_RUNS)], + ) + .await + }) + .await +} + +/// Tell the server's operator that output retention failed, for one run or for the pass; it is retried next pass. +pub(crate) fn report_retention_failure(run_id: Option, error: &ControlError) { + match run_id { + Some(run_id) => eprintln!( + "Run output retention: could not remove the output of run {run_id}; retrying next pass: {error}" + ), + None => eprintln!("Run output retention failed; retrying next pass: {error}"), + } +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs new file mode 100644 index 0000000000..77d6f796b6 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs @@ -0,0 +1,290 @@ +//! The worker side of run output: complete lines per node and stream go into batches one sender thread posts. + +use std::cell::RefCell; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Instant; + +use crate::api::errors::ClientError; +use crate::run_output::constants::{ + BATCH_TEXT_BYTES, BATCH_WINDOW, MAX_BATCH_SEGMENTS, MAX_PARTIAL_LINE_BYTES, MAX_QUEUED_BATCHES, + UPLOAD_ATTEMPTS, UTF8_CONTINUATION, UTF8_PREFIX_MASK, +}; +use crate::run_output::models::{ + OutputBatch, OutputSegment, OutputStream, RunOutputUploader, UploadShared, UploadState, +}; +use crate::worker::models::WorkerClient; + +/// The run output of this process's run; a worker process runs one run. +pub(crate) static ATTACHED: Mutex>> = Mutex::new(None); + +thread_local! { + /// The node whose code runs on this thread, keyed `:`. + pub(crate) static OUTPUT_NODE: RefCell> = const { RefCell::new(None) }; +} + +pub(crate) fn attached() -> MutexGuard<'static, Option>> { + ATTACHED.lock().unwrap_or_else(PoisonError::into_inner) +} + +impl UploadShared { + pub(crate) fn locked(&self) -> MutexGuard<'_, UploadState> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +impl UploadState { + /// Take `data` for `node`'s `stream`, holding a line until its newline unless it outgrows its limit and is cut between characters. + pub(crate) fn append(&mut self, (node, stream): (String, OutputStream), data: &[u8]) { + if self.closing.is_some() { + self.summary.dropped_bytes += data.len() as u64; + return; + } + let key = (node, stream); + let mut buffer: Vec = self.partial.remove(&key).unwrap_or_default(); + buffer.extend_from_slice(data); + let complete: usize = match buffer.iter().rposition(|byte| *byte == b'\n') { + Some(position) => position + 1, + None if buffer.len() > MAX_PARTIAL_LINE_BYTES => complete_characters(&buffer), + None => 0, + }; + let rest: Vec = buffer.split_off(complete); + if complete > 0 && buffer.last() != Some(&b'\n') { + buffer.push(b'\n'); + } + if !rest.is_empty() { + self.partial.insert(key.clone(), rest); + } + if !buffer.is_empty() { + self.push_lines(key, &String::from_utf8_lossy(&buffer)); + } + } + + /// End every held partial line, as when the run finishes. + pub(crate) fn end_lines(&mut self) { + for (key, mut buffer) in std::mem::take(&mut self.partial) { + buffer.push(b'\n'); + self.push_lines(key, &String::from_utf8_lossy(&buffer)); + } + } + + /// Add complete lines, sealing the batch before a line would overflow its size or a segment its count. + fn push_lines(&mut self, (node, stream): (String, OutputStream), text: &str) { + let node_key: Option = Some(node).filter(|node| !node.is_empty()); + for line in text.split_inclusive('\n') { + for piece in line_pieces(line) { + self.push_piece((&node_key, stream), &piece); + } + } + } + + fn push_piece(&mut self, (node_key, stream): (&Option, OutputStream), piece: &str) { + if self.batch_bytes + piece.len() > BATCH_TEXT_BYTES { + self.seal(); + } + let joins: bool = self.unreported_drops == 0 + && self + .segments + .last() + .is_some_and(|last| last.node_key == *node_key && last.stream == stream); + if joins { + if let Some(last) = self.segments.last_mut() { + last.text.push_str(piece); + } + } else { + if self.segments.len() >= MAX_BATCH_SEGMENTS { + self.seal(); + } + self.segments.push(OutputSegment { + node_key: node_key.clone(), + stream, + text: piece.to_owned(), + dropped_bytes: std::mem::take(&mut self.unreported_drops), + }); + } + self.batch_bytes += piece.len(); + self.batch_started.get_or_insert_with(Instant::now); + if self.batch_bytes >= BATCH_TEXT_BYTES { + self.seal(); + } + } + + /// Queue the open batch; a printing thread waits while too many are queued. + pub(crate) fn seal(&mut self) { + if self.segments.is_empty() { + return; + } + let segments: Vec = std::mem::take(&mut self.segments); + self.batch_bytes = 0; + self.batch_started = None; + self.queued.push_back(OutputBatch { + batch: self.next_batch, + segments, + }); + self.next_batch += 1; + } + + /// Whether the printing thread must wait for the sender before printing more. + pub(crate) fn backlogged(&self) -> bool { + self.queued.len() > MAX_QUEUED_BATCHES + } + + /// Drop the newest queued batches past the limit and count their bytes, when the sender has stalled. + pub(crate) fn shed(&mut self) { + while self.queued.len() > MAX_QUEUED_BATCHES { + let Some(batch) = self.queued.pop_back() else { + return; + }; + let bytes: u64 = batch + .segments + .iter() + .map(|segment| segment.text.len() as u64) + .sum(); + self.next_batch -= 1; + self.summary.dropped_bytes += bytes; + self.unreported_drops += bytes; + } + } + + /// Whether the open batch has waited its window. + pub(crate) fn window_passed(&self, now: Instant) -> bool { + self.batch_started + .is_some_and(|started| now.duration_since(started) >= BATCH_WINDOW) + } +} + +/// How many leading bytes end on a character boundary; an incomplete UTF-8 sequence at the end waits for the next write. +pub(crate) fn complete_characters(bytes: &[u8]) -> usize { + let tail: usize = bytes.len().min(3); + for back in 1..=tail { + let byte: u8 = bytes[bytes.len() - back]; + if byte & UTF8_PREFIX_MASK == UTF8_CONTINUATION { + continue; + } + let width: usize = (byte.leading_ones() as usize).max(1); + return if width > back { + bytes.len() - back + } else { + bytes.len() + }; + } + bytes.len() +} + +/// A line cut into pieces of at most a partial line's size at character boundaries, each ending in a newline. +pub(crate) fn line_pieces(line: &str) -> Vec> { + if line.len() <= MAX_PARTIAL_LINE_BYTES + 1 { + return vec![std::borrow::Cow::Borrowed(line)]; + } + let body: &str = line.strip_suffix('\n').unwrap_or(line); + let mut pieces: Vec> = Vec::new(); + let mut start: usize = 0; + while start < body.len() { + let mut end: usize = (start + MAX_PARTIAL_LINE_BYTES).min(body.len()); + while !body.is_char_boundary(end) { + end -= 1; + } + pieces.push(std::borrow::Cow::Owned(format!("{}\n", &body[start..end]))); + start = end; + } + pieces +} + +/// Post batches until the uploader closes and nothing is left, or its close budget is spent. +pub(crate) fn send_batches( + shared: &Arc, + client: &WorkerClient, + runtime: &tokio::runtime::Runtime, +) { + loop { + let batch: Option = { + let mut state = shared.locked(); + loop { + let now = Instant::now(); + if state.window_passed(now) || state.closing.is_some() { + state.seal(); + } + if let Some(batch) = state.queued.pop_front() { + break Some(batch); + } + if state.closing.is_some() { + break None; + } + state = shared + .wake + .wait_timeout(state, BATCH_WINDOW) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + }; + let Some(batch) = batch else { + return; + }; + let bytes: u64 = batch + .segments + .iter() + .map(|segment| segment.text.len() as u64) + .sum(); + let past_budget: bool = shared + .locked() + .closing + .is_some_and(|deadline| Instant::now() >= deadline); + let sent: Result<(), String> = if past_budget { + Err("the run finished before its last output could be sent".into()) + } else { + send(client, runtime, &batch) + }; + let mut state = shared.locked(); + shared.wake.notify_all(); + match sent { + Ok(()) => state.summary.stored_batches += 1, + Err(failure) => { + state.summary.dropped_bytes += bytes; + state.unreported_drops += bytes; + if state.summary.failure.is_none() { + state.summary.failure = Some(failure); + } + } + } + } +} + +/// Send one batch, again while the server is unreachable or busy; a refusal says why. +fn send( + client: &WorkerClient, + runtime: &tokio::runtime::Runtime, + batch: &OutputBatch, +) -> Result<(), String> { + let mut attempt: u32 = 0; + loop { + attempt += 1; + match runtime.block_on(client.publish_output_batch(batch)) { + Ok(_) => return Ok(()), + Err(ClientError::Rejected(status)) + if status == reqwest::StatusCode::NOT_FOUND + || status == reqwest::StatusCode::METHOD_NOT_ALLOWED => + { + return Err( + "the control server is older than this worker and does not accept run output; upgrade the server before its workers".into(), + ); + } + Err(error) if attempt < UPLOAD_ATTEMPTS && retryable(&error) => { + std::thread::sleep(std::time::Duration::from_millis(200 * u64::from(attempt))); + } + Err(error) => { + return Err(format!( + "the control server did not accept run output: {error}" + )); + } + } + } +} + +fn retryable(error: &ClientError) -> bool { + match error { + ClientError::Transport(_) => true, + ClientError::Rejected(status) => { + status.is_server_error() || *status == reqwest::StatusCode::TOO_MANY_REQUESTS + } + _ => false, + } +} diff --git a/crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs b/crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs new file mode 100644 index 0000000000..5e86823c09 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs @@ -0,0 +1,201 @@ +//! Indexed reads of one view of a run's output: its segments either side of a line, its size, its gap and its node summaries and marks. + +use uuid::Uuid; + +use crate::run_output::models::{ + NodeLogLine, NodeOutputSummary, OutputMark, OutputView, RunOutputIndex, SearchDirection, + StoredGap, StoredOutputTotals, StoredSegment, ViewCount, +}; +use crate::store::errors::ControlError; +use crate::store::main::query_records::query_records; +use crate::store::models::{ControlTransaction, Parameter}; + +/// The view's run, its node or the run's own key, and its stream filter; a run view filters on no node. +fn view_parameters(view: &OutputView) -> Vec { + vec![ + Parameter::Id(view.run_id), + Parameter::OptionalText(view.node.clone()), + Parameter::OptionalText(view.stream.map(|stream| stream.as_str().to_owned())), + ] +} + +/// Up to `limit` of the view's segments holding lines from `bound` onwards, or before `bound` backwards, nearest first. +pub(crate) async fn view_segments( + transaction: ControlTransaction, + view: &OutputView, + (direction, bound): (SearchDirection, i64), + limit: i64, +) -> Result<(ControlTransaction, Vec), ControlError> { + let sql: &str = match (view.node.is_some(), direction) { + (true, SearchDirection::Forward) => { + "SELECT s.node_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ + c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ + WHERE s.run_id=$1 AND s.node_key=$2 AND ($3 IS NULL OR s.stream=$3) AND s.node_line+s.line_count>$4 \ + ORDER BY s.node_line ASC LIMIT $5" + } + (true, SearchDirection::Backward) => { + "SELECT s.node_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ + c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ + WHERE s.run_id=$1 AND s.node_key=$2 AND ($3 IS NULL OR s.stream=$3) AND s.node_line<$4 \ + ORDER BY s.node_line DESC LIMIT $5" + } + (false, SearchDirection::Forward) => { + "SELECT s.run_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ + c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ + WHERE s.run_id=$1 AND $2 IS NULL AND ($3 IS NULL OR s.stream=$3) AND s.run_line+s.line_count>$4 \ + ORDER BY s.run_line ASC LIMIT $5" + } + (false, SearchDirection::Backward) => { + "SELECT s.run_line AS first_line, s.line_count, s.node_key, s.stream, s.text_offset, s.text_bytes, \ + c.object_key, c.text_bytes AS chunk_text_bytes, c.received_at FROM sqb_run_output_segments s \ + JOIN sqb_run_output_chunks c ON c.run_id=s.run_id AND c.chunk=s.chunk \ + WHERE s.run_id=$1 AND $2 IS NULL AND ($3 IS NULL OR s.stream=$3) AND s.run_line<$4 \ + ORDER BY s.run_line DESC LIMIT $5" + } + }; + let mut parameters: Vec = view_parameters(view); + parameters.extend([Parameter::Integer(bound), Parameter::Integer(limit)]); + query_records(transaction, sql, parameters).await +} + +/// The view's highest line number: the node's line count, or the run's. +pub(crate) async fn view_line_count( + transaction: ControlTransaction, + view: &OutputView, +) -> Result<(ControlTransaction, i64), ControlError> { + let (transaction, rows): (ControlTransaction, Vec) = match &view.node { + Some(node) => { + query_records( + transaction, + "SELECT CAST(COALESCE(SUM(line_count), 0) AS BIGINT) AS count FROM sqb_run_output_streams \ + WHERE run_id=$1 AND node_key=$2", + vec![Parameter::Id(view.run_id), Parameter::Text(node.clone())], + ) + .await? + } + None => { + query_records( + transaction, + "SELECT line_count AS count FROM sqb_run_output WHERE run_id=$1", + vec![Parameter::Id(view.run_id)], + ) + .await? + } + }; + Ok((transaction, rows.first().map_or(0, |row| row.count))) +} + +/// How many chunks hold a node view's lines. +pub(crate) async fn view_chunk_count( + transaction: ControlTransaction, + view: &OutputView, +) -> Result<(ControlTransaction, i64), ControlError> { + let (transaction, rows): (ControlTransaction, Vec) = query_records( + transaction, + "SELECT CAST(COUNT(DISTINCT s.chunk) AS BIGINT) AS count FROM sqb_run_output_segments s \ + WHERE s.run_id=$1 AND s.node_key=$2 AND ($3 IS NULL OR s.stream=$3)", + view_parameters(view), + ) + .await?; + Ok((transaction, rows.first().map_or(0, |row| row.count))) +} + +/// Where a size cap left a gap in the view: its first line after the gap and how many lines of the view were left out. +pub(crate) async fn view_gap( + transaction: ControlTransaction, + view: &OutputView, +) -> Result<(ControlTransaction, Option<(i64, i64)>), ControlError> { + let sql: &str = if view.node.is_some() { + "SELECT (SELECT MIN(s.node_line) FROM sqb_run_output_segments s JOIN sqb_run_output_chunks c \ + ON c.run_id=s.run_id AND c.chunk=s.chunk WHERE s.run_id=$1 AND s.node_key=$2 \ + AND ($3 IS NULL OR s.stream=$3) AND c.part='tail') AS first_tail, \ + (SELECT MAX(s.node_line+s.line_count) FROM sqb_run_output_segments s JOIN sqb_run_output_chunks c \ + ON c.run_id=s.run_id AND c.chunk=s.chunk WHERE s.run_id=$1 AND s.node_key=$2 \ + AND ($3 IS NULL OR s.stream=$3) AND c.part='head') AS after_head, \ + (SELECT omitted_lines FROM sqb_run_output WHERE run_id=$1) AS omitted_lines" + } else { + "SELECT (SELECT MIN(s.run_line) FROM sqb_run_output_segments s JOIN sqb_run_output_chunks c \ + ON c.run_id=s.run_id AND c.chunk=s.chunk WHERE s.run_id=$1 AND $2 IS NULL \ + AND ($3 IS NULL OR s.stream=$3) AND c.part='tail') AS first_tail, \ + (SELECT MAX(s.run_line+s.line_count) FROM sqb_run_output_segments s JOIN sqb_run_output_chunks c \ + ON c.run_id=s.run_id AND c.chunk=s.chunk WHERE s.run_id=$1 AND $2 IS NULL \ + AND ($3 IS NULL OR s.stream=$3) AND c.part='head') AS after_head, \ + (SELECT omitted_lines FROM sqb_run_output WHERE run_id=$1) AS omitted_lines" + }; + let (transaction, rows): (ControlTransaction, Vec) = + query_records(transaction, sql, view_parameters(view)).await?; + let gap = rows.first().and_then(|row| gap_of(*row)); + Ok((transaction, gap)) +} + +/// The gap a stored gap row describes: lines left out before the view's first kept tail line. +fn gap_of(row: StoredGap) -> Option<(i64, i64)> { + let first: i64 = row.first_tail?; + let left_out: i64 = first - row.after_head.unwrap_or(1); + (row.omitted_lines.unwrap_or_default() > 0 && left_out > 0).then_some((first, left_out)) +} + +/// Each node's line and byte counts, by node key. +async fn node_summaries( + transaction: ControlTransaction, + run_id: Uuid, +) -> Result<(ControlTransaction, Vec), ControlError> { + query_records(transaction, + "SELECT node_key, CAST(SUM(line_count) AS BIGINT) AS line_count, \ + CAST(SUM(CASE WHEN stream='stdout' THEN line_count ELSE 0 END) AS BIGINT) AS stdout_lines, \ + CAST(SUM(CASE WHEN stream='stderr' THEN line_count ELSE 0 END) AS BIGINT) AS stderr_lines, \ + CAST(SUM(text_bytes) AS BIGINT) AS text_bytes FROM sqb_run_output_streams WHERE run_id=$1 \ + GROUP BY node_key ORDER BY node_key", + vec![Parameter::Id(run_id)]).await +} + +/// One node's error and warning lines, by line. +async fn node_marks( + transaction: ControlTransaction, + (run_id, node): (Uuid, &str), +) -> Result<(ControlTransaction, Vec), ControlError> { + query_records( + transaction, + "SELECT node_line AS line, stream, level, text FROM sqb_run_output_marks \ + WHERE run_id=$1 AND node_key=$2 ORDER BY node_line", + vec![Parameter::Id(run_id), Parameter::Text(node.into())], + ) + .await +} + +/// The run's output index, with `node`'s marks when one is named. +pub(crate) async fn output_index( + transaction: ControlTransaction, + (run_id, node): (Uuid, Option<&str>), +) -> Result<(ControlTransaction, RunOutputIndex), ControlError> { + let (transaction, nodes) = node_summaries(transaction, run_id).await?; + let (transaction, totals): (ControlTransaction, Vec) = query_records( + transaction, + "SELECT line_count, omitted_bytes, omitted_lines, dropped_bytes FROM sqb_run_output WHERE run_id=$1", + vec![Parameter::Id(run_id)], + ) + .await?; + let (transaction, logs): (ControlTransaction, Vec) = query_records(transaction, + "SELECT node_key, level, message, logged_at FROM sqb_run_node_logs WHERE run_id=$1 ORDER BY logged_at, event_id", + vec![Parameter::Id(run_id)]).await?; + let (transaction, marks) = match node { + Some(node) => node_marks(transaction, (run_id, node)).await?, + None => (transaction, Vec::new()), + }; + let totals: StoredOutputTotals = totals.into_iter().next().unwrap_or_default(); + Ok(( + transaction, + RunOutputIndex { + nodes, + line_count: totals.line_count, + omitted_bytes: totals.omitted_bytes, + omitted_lines: totals.omitted_lines, + dropped_bytes: totals.dropped_bytes, + logs, + marks, + }, + )) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/constants.rs b/crates/sqlbuild-orchestration/src/run_output/constants.rs new file mode 100644 index 0000000000..df94f20058 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/constants.rs @@ -0,0 +1,107 @@ +//! Limits of run output batches, pages and searches, and the names its index stores. + +/// The node key of lines a run printed outside any node. +pub const RUN_OUTPUT_NODE: &str = "run"; + +pub const STDOUT_STREAM: &str = "stdout"; + +pub const STDERR_STREAM: &str = "stderr"; + +/// A worker sends a batch once its text reaches this many bytes. +pub const BATCH_TEXT_BYTES: usize = 4 * 1024 * 1024; + +/// A worker sends a batch at least this often while output arrives. +pub const BATCH_WINDOW: std::time::Duration = std::time::Duration::from_secs(2); + +/// A batch the server accepts carries at most this many text bytes. +pub const MAX_BATCH_TEXT_BYTES: usize = 8 * 1024 * 1024; + +/// A batch the server accepts carries at most this many segments. +pub const MAX_BATCH_SEGMENTS: usize = 4096; + +/// The most rows one page of output returns. +pub const MAX_PAGE_ROWS: u32 = 2000; + +/// Rows one page returns when the reader names no limit. +pub const DEFAULT_PAGE_ROWS: u32 = 500; + +/// A folding page reads at most this many lines past its last row to finish a run of similar lines. +pub const COLLAPSE_SCAN_LINES: i64 = 100_000; + +/// Four or more lines that are the same but for their numbers fold into one row. +pub const MIN_SIMILAR_LINES: usize = 4; + +/// Lines this close to the line a reader jumped to never fold. +pub const AROUND_OPEN_LINES: i64 = 3; + +/// A mark keeps at most this many bytes of its line. +pub const MARK_TEXT_BYTES: usize = 300; + +/// A page or search reads a view's segments this many at a time. +pub(crate) const SEGMENT_BATCH: i64 = 64; + +pub(crate) const ERROR_LEVEL: &str = "error"; + +pub(crate) const WARNING_LEVEL: &str = "warning"; + +/// The most chunks one search reads before it hands back where to continue; a view this small is searched whole, with a count. +pub const SEARCH_CHUNKS: usize = 64; + +/// Each node's stream keeps at most this many marked lines. +pub const MARKED_LINES: usize = 10_000; + +/// The zstd level each chunk is written at. +pub const ZSTD_LEVEL: i32 = 3; + +pub(crate) const HEAD_PART: &str = "head"; + +pub(crate) const TAIL_PART: &str = "tail"; + +/// The longest `ctx.log` message a worker reports; longer ones end in an ellipsis. +pub const NODE_LOG_MESSAGE_BYTES: usize = 4096; + +/// The most `ctx.log` lines a worker reports per node. +pub const NODE_LOGS_PER_NODE: usize = 200; + +/// The folder an output store defaults to, beside a SQLite control store. +pub const DEFAULT_OUTPUT_FOLDER: &str = "output"; + +/// Names the user's state folder when it holds an absolute path. +pub(crate) const STATE_HOME_VARIABLE: &str = "XDG_STATE_HOME"; + +/// The user's state folder within their home, when `XDG_STATE_HOME` doesn't name one. +pub(crate) const HOME_STATE_FOLDER: &str = ".local/state"; + +/// SQLBuild's folder within the user's state folder. +pub(crate) const STATE_SUBFOLDER: &str = "sqlbuild"; + +/// Why run output has no default folder with PostgreSQL. +pub(crate) const NO_STATE_HOME: &str = "run output has no default folder because this user has no home directory; set HOME or XDG_STATE_HOME to an absolute path, or set [output] store"; + +/// A worker holds at most this many batches waiting to send; past them the printing thread waits. +pub const MAX_QUEUED_BATCHES: usize = 4; + +/// How long a printing thread waits for a full queue to drain before it drops the newest batches and counts them. +pub const UPLOAD_STALL: std::time::Duration = std::time::Duration::from_secs(30); + +/// A line longer than this is sent in pieces rather than held until its newline. +pub const MAX_PARTIAL_LINE_BYTES: usize = 1024 * 1024; + +/// A batch is sent at most this many times while the server is unreachable or busy. +pub const UPLOAD_ATTEMPTS: u32 = 3; + +/// How long a finishing worker waits for its last batches to send. +pub const UPLOAD_CLOSE_BUDGET: std::time::Duration = std::time::Duration::from_secs(30); + +pub(crate) const FILE_SCHEME: &str = "file://"; + +pub(crate) const S3_SCHEME: &str = "s3://"; + +/// Retention removes the output of at most this many runs per pass. +pub(crate) const PRUNE_RUNS: i64 = 100; + +/// The top two bits of a UTF-8 byte, which mark a continuation byte when they are `10`. +pub(crate) const UTF8_PREFIX_MASK: u8 = 0b1100_0000; + +/// The top two bits of a UTF-8 continuation byte. +pub(crate) const UTF8_CONTINUATION: u8 = 0b1000_0000; diff --git a/crates/sqlbuild-orchestration/src/run_output/main/download_person_output.rs b/crates/sqlbuild-orchestration/src/run_output/main/download_person_output.rs new file mode 100644 index 0000000000..88c305d930 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/download_person_output.rs @@ -0,0 +1,56 @@ +//! A node's whole output as text, both streams in the order printed or one of them, read a batch of segments at a time so a large log never sits in memory; the download is audited. + +use futures_util::Stream; +use serde_json::json; + +use crate::credentials::models::Action; +use crate::run_output::_helpers::pages::text_after; +use crate::run_output::_helpers::views::view_line_count; +use crate::run_output::models::{OutputDownloadQuery, OutputStore, OutputView}; +use crate::run_output::types::PersonRunRead; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; +use crate::warehouse_history::main::read_run_evidence::read_run_evidence; + +/// `None` when the run is not in this location and target. +pub async fn download_person_output( + store: &ControlStore, + output: &OutputStore, + (credentials, run, default_role): PersonRunRead<'_>, + query: &OutputDownloadQuery, +) -> Result> + Send + 'static>, ControlError> +{ + let view = OutputView { + run_id: run.2, + node: Some(query.node.clone()), + stream: query.stream, + }; + let Some(_) = read_run_evidence( + store, + credentials, + (run, default_role, Action::ViewEvidence), + ( + ( + "output.download", + async |transaction, _| view_line_count(transaction, &view).await, + |lines: &i64| json!({"node": query.node, "stream": query.stream, "lines": lines}), + ), + None, + ), + ) + .await? + else { + return Ok(None); + }; + Ok(Some(futures_util::stream::unfold( + (store.clone(), output.clone(), view, Some(1_i64)), + async |(store, output, view, bound)| { + let read = text_after((&store, &output), &view, bound?).await; + match read { + Ok(Some((text, next))) => Some((Ok(text), (store, output, view, Some(next)))), + Ok(None) => None, + Err(error) => Some((Err(error), (store, output, view, None))), + } + }, + ))) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/enter_output_node.rs b/crates/sqlbuild-orchestration/src/run_output/main/enter_output_node.rs new file mode 100644 index 0000000000..ddb297d5b4 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/enter_output_node.rs @@ -0,0 +1,8 @@ +//! Name the node whose code runs on this thread, so the output it prints is filed under it. + +use crate::run_output::_helpers::upload::OUTPUT_NODE; + +/// Returns the node named before, to restore when the node's code returns; `None` files output under the run. +pub fn enter_output_node(node_key: Option) -> Option { + OUTPUT_NODE.with(|node| node.replace(node_key)) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/finish_output_upload.rs b/crates/sqlbuild-orchestration/src/run_output/main/finish_output_upload.rs new file mode 100644 index 0000000000..655da55e3a --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/finish_output_upload.rs @@ -0,0 +1,27 @@ +//! Send this process's last run output within a budget, stop its sender and report what was lost. + +use std::time::{Duration, Instant}; + +use crate::run_output::_helpers::upload::attached; +use crate::run_output::models::UploadSummary; + +/// `None` when this process sent no run output. +pub fn finish_output_upload(budget: Duration) -> Option { + let uploader = attached().take()?; + { + let mut state = uploader.shared.locked(); + state.end_lines(); + state.closing = Some(Instant::now() + budget); + } + uploader.shared.wake.notify_all(); + let sender = uploader + .sender + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + if let Some(sender) = sender { + drop(sender.join()); + } + let summary = uploader.shared.locked().summary.clone(); + Some(summary) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/forward_output.rs b/crates/sqlbuild-orchestration/src/run_output/main/forward_output.rs new file mode 100644 index 0000000000..dcb8ad4b64 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/forward_output.rs @@ -0,0 +1,16 @@ +//! Hand bytes a process stream accepted to this process's run output, under the node running on this thread. + +use crate::run_output::_helpers::upload::{OUTPUT_NODE, attached}; +use crate::run_output::models::OutputStream; + +/// Never waits: call it under the lock that orders output, then `wait_for_output_room` outside it; a no-op outside a worker. +pub fn forward_output(stream: OutputStream, data: &[u8]) { + let Some(uploader) = attached().clone() else { + return; + }; + let node: String = OUTPUT_NODE + .with(|node| node.borrow().clone()) + .unwrap_or_default(); + uploader.shared.locked().append((node, stream), data); + uploader.shared.wake.notify_all(); +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/mod.rs b/crates/sqlbuild-orchestration/src/run_output/main/mod.rs new file mode 100644 index 0000000000..c80c2a51d8 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/mod.rs @@ -0,0 +1,12 @@ +pub mod download_person_output; +pub mod enter_output_node; +pub mod finish_output_upload; +pub mod forward_output; +pub mod open_output_store; +pub mod prune_run_output; +pub mod publish_output_batch; +pub mod read_person_output_index; +pub mod read_person_output_page; +pub mod search_person_output; +pub mod start_output_upload; +pub mod wait_for_output_room; diff --git a/crates/sqlbuild-orchestration/src/run_output/main/open_output_store.rs b/crates/sqlbuild-orchestration/src/run_output/main/open_output_store.rs new file mode 100644 index 0000000000..934d6171b6 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/open_output_store.rs @@ -0,0 +1,64 @@ +//! Open the output store `server.toml` names, or the default folder for the control store. + +use std::path::PathBuf; +use std::sync::Arc; + +use object_store::ObjectStore; +use object_store::aws::AmazonS3Builder; +use object_store::local::LocalFileSystem; +use object_store::path::Path; + +use crate::run_output::_helpers::folders::{default_folder, user_folders}; +use crate::run_output::constants::{FILE_SCHEME, S3_SCHEME}; +use crate::run_output::models::{OutputSettings, OutputStore}; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; + +/// A local folder is created when missing; an S3 store takes its credentials from the standard AWS environment or role. +pub fn open_output_store( + settings: &OutputSettings, + control: &ControlStore, +) -> Result { + let mut location: String = match &settings.store { + Some(location) => location.clone(), + None => format!( + "{FILE_SCHEME}{}", + default_folder(control, user_folders())?.display() + ), + }; + let (objects, prefix): (Arc, Path) = + if let Some(folder) = location.strip_prefix(FILE_SCHEME) { + std::fs::create_dir_all(folder)?; + let resolved: PathBuf = std::path::absolute(folder)?; + location = format!("{FILE_SCHEME}{}", resolved.display()); + ( + Arc::new(LocalFileSystem::new_with_prefix(resolved)?), + Path::default(), + ) + } else if let Some(rest) = location.strip_prefix(S3_SCHEME) { + let (bucket, prefix) = rest.split_once('/').unwrap_or((rest, "")); + if bucket.is_empty() { + return Err(ControlError::Invalid( + "[output] store needs a bucket, as in s3://bucket/prefix".into(), + )); + } + ( + Arc::new( + AmazonS3Builder::from_env() + .with_bucket_name(bucket) + .build()?, + ), + Path::from(prefix.trim_matches('/')), + ) + } else { + return Err(ControlError::Invalid(format!( + "[output] store must be a file:// folder or an s3:// bucket, not {location}" + ))); + }; + Ok(OutputStore { + objects, + prefix, + location, + max_bytes_per_run: settings.max_bytes_per_run, + }) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/prune_run_output.rs b/crates/sqlbuild-orchestration/src/run_output/main/prune_run_output.rs new file mode 100644 index 0000000000..70b99c5da4 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/prune_run_output.rs @@ -0,0 +1,24 @@ +//! Finished runs past `run_output_days` lose their output; the run and its node logs stay. + +use crate::run_output::_helpers::prune::{expired_runs, prune_run, report_retention_failure}; +use crate::run_output::models::{ExpiredRun, OutputStore}; +use crate::store::models::ControlStore; + +/// How many runs lost their output; a failure is reported on stderr and retried next pass, never stopping other retention. +pub async fn prune_run_output(store: &ControlStore, output: &OutputStore, days: u16) -> usize { + let expired: Vec = match expired_runs(store, days).await { + Ok(expired) => expired, + Err(error) => { + report_retention_failure(None, &error); + return 0; + } + }; + let mut pruned: usize = 0; + for ExpiredRun { run_id } in &expired { + match prune_run(store, output, *run_id).await { + Ok(()) => pruned += 1, + Err(error) => report_retention_failure(Some(*run_id), &error), + } + } + pruned +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/publish_output_batch.rs b/crates/sqlbuild-orchestration/src/run_output/main/publish_output_batch.rs new file mode 100644 index 0000000000..5691981177 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/publish_output_batch.rs @@ -0,0 +1,49 @@ +//! A worker's batch of output: one zstd chunk in the output store, indexed under the worker's active claim. + +use uuid::Uuid; + +use crate::run_output::_helpers::index::{batch_stored, record_chunk}; +use crate::run_output::_helpers::objects::{chunk_key, delete_chunks, put_chunk}; +use crate::run_output::_helpers::prepare::{checked, prepared}; +use crate::run_output::models::{OutputBatch, OutputBatchReceipt, OutputStore}; +use crate::runs::main::execution::require_active_claim::require_active_claim; +use crate::store::errors::ControlError; +use crate::store::main::{begin::begin, commit::commit}; +use crate::store::models::{ControlStore, TransactionMode}; + +/// The chunk is written before its index, so a failed index leaves only an object retention removes; a retried batch is stored once. +pub async fn publish_output_batch( + store: &ControlStore, + output: &OutputStore, + (run_id, claim_id): (Uuid, Uuid), + batch: OutputBatch, +) -> Result { + checked(&batch)?; + let transaction = begin(store, TransactionMode::Read).await?; + let transaction = require_active_claim(transaction, (run_id, claim_id)).await?; + let (transaction, stored) = batch_stored(transaction, (run_id, claim_id), batch.batch).await?; + commit(transaction).await?; + if stored { + return Ok(OutputBatchReceipt { stored: false }); + } + let key = chunk_key(output, (run_id, claim_id), batch.batch); + let object_key: String = key.to_string(); + let (chunk, compressed) = + tokio::task::spawn_blocking(move || prepared((run_id, claim_id), &batch, object_key)) + .await??; + put_chunk(output, &key, compressed).await?; + let half: Option = output + .max_bytes_per_run + .map(|limit| i64::try_from(limit / 2).unwrap_or(i64::MAX)); + let transaction = begin(store, TransactionMode::Write).await?; + let transaction = require_active_claim(transaction, (run_id, claim_id)).await?; + let (transaction, stored) = batch_stored(transaction, (run_id, claim_id), chunk.batch).await?; + if stored { + commit(transaction).await?; + return Ok(OutputBatchReceipt { stored: false }); + } + let (transaction, dropped) = record_chunk(transaction, &chunk, half).await?; + commit(transaction).await?; + delete_chunks(output, &dropped).await?; + Ok(OutputBatchReceipt { stored: true }) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_index.rs b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_index.rs new file mode 100644 index 0000000000..f4dab7c80f --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_index.rs @@ -0,0 +1,32 @@ +//! How much each node of a run printed, what its nodes logged, and one node's error and warning lines; output can quote warehouse data, so it needs view.evidence. + +use serde_json::json; + +use crate::credentials::models::Action; +use crate::run_output::_helpers::views::output_index; +use crate::run_output::models::RunOutputIndex; +use crate::run_output::types::PersonRunRead; +use crate::runs::constants::REPEATED_READ_AUDIT; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; +use crate::warehouse_history::main::read_run_evidence::read_run_evidence; + +/// `None` when the run is not in this location and target; `node` names whose marks to include; each read is audited. +pub async fn read_person_output_index( + store: &ControlStore, + (credentials, run, default_role): PersonRunRead<'_>, + node: Option<&str>, +) -> Result, ControlError> { + let run_id = run.2; + read_run_evidence( + store, + credentials, + (run, default_role, Action::ViewEvidence), + (( + "output.index", + async move |transaction, _| output_index(transaction, (run_id, node)).await, + |index: &RunOutputIndex| json!({"nodes": index.nodes.len(), "logs": index.logs.len(), "node": node}), + ), Some(REPEATED_READ_AUDIT)), + ) + .await +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_page.rs b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_page.rs new file mode 100644 index 0000000000..a193627e62 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_page.rs @@ -0,0 +1,65 @@ +//! A page of a node's output, or of the whole run's, forwards, backwards or from the end, with similar lines folded on request; each read needs view.evidence and is audited. + +use serde_json::json; + +use crate::credentials::models::Action; +use crate::run_output::_helpers::pages::{page_neighbours, page_rows, page_start}; +use crate::run_output::_helpers::views::view_line_count; +use crate::run_output::constants::{DEFAULT_PAGE_ROWS, MAX_PAGE_ROWS}; +use crate::run_output::models::{OutputPage, OutputPageQuery, OutputStore, OutputView, ViewReader}; +use crate::run_output::types::PersonRunRead; +use crate::runs::constants::REPEATED_READ_AUDIT; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; +use crate::warehouse_history::main::read_run_evidence::read_run_evidence; + +/// `None` when the run is not in this location and target; output nobody printed is an empty page. +pub async fn read_person_output_page( + store: &ControlStore, + output: &OutputStore, + (credentials, run, default_role): PersonRunRead<'_>, + query: &OutputPageQuery, +) -> Result, ControlError> { + let view = OutputView { + run_id: run.2, + node: query.node.clone(), + stream: query.stream, + }; + let limit: usize = usize::try_from( + query + .limit + .unwrap_or(DEFAULT_PAGE_ROWS) + .clamp(1, MAX_PAGE_ROWS), + ) + .unwrap_or(1); + let Some(line_count) = read_run_evidence( + store, + credentials, + (run, default_role, Action::ViewEvidence), + (( + "output.page", + async |transaction, _| view_line_count(transaction, &view).await, + |_: &i64| json!({"node": query.node, "stream": query.stream, "from": query.from, "before": query.before, "tail": query.tail}), + ), Some(REPEATED_READ_AUDIT)), + ) + .await? + else { + return Ok(None); + }; + let start = page_start(query, line_count)?; + let mut reader = ViewReader::open((store, output), &view, start).await?; + let page = page_rows(&mut reader, limit, (query.collapse, query.around)).await?; + let (from, to) = ( + page.low.unwrap_or(start.1), + page.high.map_or(start.1, |high| high + 1), + ); + let (next, previous) = page_neighbours(store, &view, (from, to)).await?; + Ok(Some(OutputPage { + rows: page.rows, + line_count, + from, + to, + next, + previous, + })) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/search_person_output.rs b/crates/sqlbuild-orchestration/src/run_output/main/search_person_output.rs new file mode 100644 index 0000000000..c17d81961b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/search_person_output.rs @@ -0,0 +1,67 @@ +//! Search a node's output for text, case-insensitively, from a line forwards or backwards; each search needs view.evidence and is audited. + +use serde_json::json; + +use crate::credentials::models::Action; +use crate::run_output::_helpers::pages::{search_part, search_whole}; +use crate::run_output::_helpers::views::view_chunk_count; +use crate::run_output::constants::SEARCH_CHUNKS; +use crate::run_output::models::{ + OutputSearch, OutputSearchQuery, OutputStore, OutputView, SearchDirection, ViewReader, +}; +use crate::run_output::types::PersonRunRead; +use crate::store::errors::ControlError; +use crate::store::models::ControlStore; +use crate::warehouse_history::main::read_run_evidence::read_run_evidence; + +/// `None` when the run is not in this location and target; output small enough is searched whole, with a count, and a larger one a bounded part at a time. +pub async fn search_person_output( + store: &ControlStore, + output: &OutputStore, + (credentials, run, default_role): PersonRunRead<'_>, + query: &OutputSearchQuery, +) -> Result, ControlError> { + let needle: String = query.text.to_lowercase(); + if needle.is_empty() { + return Err(ControlError::Invalid("search text is empty".into())); + } + let view = OutputView { + run_id: run.2, + node: Some(query.node.clone()), + stream: query.stream, + }; + let Some(chunks) = read_run_evidence( + store, + credentials, + (run, default_role, Action::ViewEvidence), + ( + ( + "output.search", + async |transaction, _| view_chunk_count(transaction, &view).await, + |_: &i64| json!({"node": query.node, "stream": query.stream}), + ), + None, + ), + ) + .await? + else { + return Ok(None); + }; + let (from, direction) = ( + query.from.unwrap_or(1).max(1), + query.direction.unwrap_or_default(), + ); + if chunks <= i64::try_from(SEARCH_CHUNKS).unwrap_or(i64::MAX) { + let mut reader = + ViewReader::open((store, output), &view, (SearchDirection::Forward, 1)).await?; + return Ok(Some( + search_whole(&mut reader, &needle, (from, direction)).await?, + )); + } + let bound: i64 = match direction { + SearchDirection::Forward => from, + SearchDirection::Backward => from + 1, + }; + let mut reader = ViewReader::open((store, output), &view, (direction, bound)).await?; + Ok(Some(search_part(&mut reader, &needle).await?)) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/start_output_upload.rs b/crates/sqlbuild-orchestration/src/run_output/main/start_output_upload.rs new file mode 100644 index 0000000000..89fc0c1d46 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/start_output_upload.rs @@ -0,0 +1,33 @@ +//! Start sending this process's run output to the server, on a thread with its own HTTP client. + +use std::sync::{Arc, Mutex}; + +use crate::run_output::_helpers::upload::{attached, send_batches}; +use crate::run_output::models::{RunOutputUploader, UploadShared}; +use crate::worker::errors::WorkerError; +use crate::worker::models::WorkerClient; + +/// Every byte captured from now on is sent under `client`'s claim until `finish_output_upload`. +pub fn start_output_upload(client: &WorkerClient) -> Result, WorkerError> { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let independent = { + let _entered = runtime.enter(); + WorkerClient { + connection: client.connection.independent()?, + ..client.clone() + } + }; + let shared: Arc = Arc::default(); + let sending: Arc = Arc::clone(&shared); + let sender = std::thread::Builder::new() + .name("sqlbuild-run-output".into()) + .spawn(move || send_batches(&sending, &independent, &runtime))?; + let uploader = Arc::new(RunOutputUploader { + shared, + sender: Mutex::new(Some(sender)), + }); + *attached() = Some(Arc::clone(&uploader)); + Ok(uploader) +} diff --git a/crates/sqlbuild-orchestration/src/run_output/main/wait_for_output_room.rs b/crates/sqlbuild-orchestration/src/run_output/main/wait_for_output_room.rs new file mode 100644 index 0000000000..66cff26d91 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/main/wait_for_output_room.rs @@ -0,0 +1,28 @@ +//! Hold a printing thread while the sender is behind, so output is not lost to a slow server. + +use std::sync::PoisonError; +use std::time::Instant; + +use crate::run_output::_helpers::upload::attached; +use crate::run_output::constants::UPLOAD_STALL; + +/// Waits while too many batches are queued (only a sender stalled past `UPLOAD_STALL` loses output); call it holding no lock and no GIL. +pub fn wait_for_output_room() { + let Some(uploader) = attached().clone() else { + return; + }; + let mut state = uploader.shared.locked(); + let deadline: Instant = Instant::now() + UPLOAD_STALL; + while state.backlogged() { + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + state.shed(); + break; + }; + state = uploader + .shared + .wake + .wait_timeout(state, left) + .unwrap_or_else(PoisonError::into_inner) + .0; + } +} diff --git a/crates/sqlbuild-orchestration/src/run_output/mod.rs b/crates/sqlbuild-orchestration/src/run_output/mod.rs new file mode 100644 index 0000000000..74b3def752 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/mod.rs @@ -0,0 +1,11 @@ +//! A run's bulk output in zstd objects in an output store, with a small index in the control store. + +pub(crate) mod _helpers; +pub mod constants; +pub mod main; +pub mod models; +pub(crate) mod types; + +#[cfg(test)] +#[path = "../../tests/run_output/test_contracts.rs"] +pub(crate) mod tests; diff --git a/crates/sqlbuild-orchestration/src/run_output/models.rs b/crates/sqlbuild-orchestration/src/run_output/models.rs new file mode 100644 index 0000000000..2b7d6ca348 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/models.rs @@ -0,0 +1,466 @@ +//! Worker output batches, the store that keeps them, and the index, pages and searches people read. + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +/// Where a server keeps run output: a local folder or an S3 prefix, and how much of a run it keeps. +#[derive(Clone, Debug)] +pub struct OutputStore { + pub(crate) objects: Arc, + pub(crate) prefix: object_store::path::Path, + pub(crate) location: String, + pub(crate) max_bytes_per_run: Option, +} + +impl OutputStore { + /// The store's location as configured, such as `file:///var/lib/sqlbuild/output`. + #[must_use] + pub fn location(&self) -> &str { + &self.location + } + + /// The resolved folder of a local store; `None` for S3. + #[must_use] + pub fn local_folder(&self) -> Option<&std::path::Path> { + self.location + .strip_prefix(crate::run_output::constants::FILE_SCHEME) + .map(std::path::Path::new) + } +} + +/// `server.toml`'s `[output]`: the store's URL and the most text kept per run. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct OutputSettings { + /// `file:///path` or `s3://bucket/prefix`; `None` keeps output in `output` beside a SQLite control store. + pub store: Option, + pub max_bytes_per_run: Option, +} + +/// One process stream. +#[derive( + Clone, + Copy, + Debug, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + utoipa::ToSchema, +)] +#[serde(rename_all = "snake_case")] +pub enum OutputStream { + Stdout, + Stderr, +} + +impl OutputStream { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Stdout => crate::run_output::constants::STDOUT_STREAM, + Self::Stderr => crate::run_output::constants::STDERR_STREAM, + } + } +} + +/// What a worker printed in one batch window, a segment per node and stream in the order printed. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct OutputBatch { + /// The worker's batch number within its claim, from 0; a retried batch is stored once. + pub batch: u64, + pub segments: Vec, +} + +/// Complete lines one node printed to one stream, each ending in a newline. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct OutputSegment { + /// The node that printed the lines, keyed `:`; `None` for lines printed outside a node. + pub node_key: Option, + pub stream: OutputStream, + pub text: String, + /// Bytes the worker dropped just before these lines because it could not send them fast enough. + #[serde(default)] + pub dropped_bytes: u64, +} + +/// Whether the server stored a batch; a retry of a stored batch is not stored again. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct OutputBatchReceipt { + pub stored: bool, +} + +/// What a run printed, per node, without its text; one node's error and warning lines; and what a size cap left out. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct RunOutputIndex { + pub nodes: Vec, + /// Lines the whole run printed, numbered in the order printed. + pub line_count: i64, + /// Bytes and lines past `max_bytes_per_run` that were dropped between the run's first and last parts. + pub omitted_bytes: i64, + pub omitted_lines: i64, + /// Bytes the worker dropped because it could not send them fast enough. + pub dropped_bytes: i64, + /// Lines the run's nodes logged with `ctx.log`, oldest first. + pub logs: Vec, + /// The named node's lines that look like errors or warnings, by line; empty when no node is named. + pub marks: Vec, +} + +/// How much one node printed: its lines, numbered across both streams, and its bytes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct NodeOutputSummary { + /// The node key, or `run` for lines printed outside any node. + pub node_key: String, + pub line_count: i64, + pub stdout_lines: i64, + pub stderr_lines: i64, + pub text_bytes: i64, +} + +/// A line that looks like an error, such as a traceback, or a warning; each stream keeps at most 10,000. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct OutputMark { + /// The line in the node's numbering. + pub line: i64, + pub stream: OutputStream, + pub level: OutputLevel, + /// The line's text, at most 300 bytes. + pub text: String, +} + +/// How a printed line reads: as an error or as a warning. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum OutputLevel { + Error, + Warning, +} + +impl OutputLevel { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Error => crate::run_output::constants::ERROR_LEVEL, + Self::Warning => crate::run_output::constants::WARNING_LEVEL, + } + } +} + +/// One line a node logged with `ctx.log`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct NodeLogLine { + pub node_key: String, + pub level: String, + pub message: String, + pub logged_at: chrono::DateTime, +} + +/// A page of a node's output, numbered across its two streams, or of the whole run's output, numbered in the order printed. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +pub struct OutputPageQuery { + /// The node key, or `run`; leave it out to read the whole run's output. + pub node: Option, + /// Only this stream's lines, keeping their numbers. + pub stream: Option, + /// Read forwards from this line, from 1. + pub from: Option, + /// Read the rows that end just before this line. + pub before: Option, + /// Read the last rows. + #[serde(default)] + pub tail: bool, + /// How many rows to read, at most 2,000. + pub limit: Option, + /// Fold four or more lines that are the same but for their numbers into one row. + #[serde(default)] + pub collapse: bool, + /// A line to keep open, with three lines either side, when folding. + pub around: Option, +} + +/// Rows covering lines `from` up to `to`, and where the pages before and after start. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct OutputPage { + pub rows: Vec, + /// The highest line number of the node, or of the run. + pub line_count: i64, + /// The first line the rows cover. + pub from: i64, + /// The line after the last the rows cover. + pub to: i64, + /// `from` for the next page, when there are later lines. + pub next: Option, + /// `before` for the previous page, when there are earlier lines. + pub previous: Option, +} + +/// A line, or a run of lines that are the same but for their numbers, folded into one row. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum OutputRow { + Line { + line: OutputLine, + }, + Similar { + from: i64, + count: i64, + sample: OutputLine, + }, +} + +/// One stored line; lines a size cap left out just before it are counted on it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct OutputLine { + pub number: i64, + /// The node that printed it, or `run`. + pub node_key: String, + pub stream: OutputStream, + pub text: String, + /// When the server received the batch holding the line, within a few seconds of its printing. + pub at: chrono::DateTime, + pub level: Option, + #[serde( + default, + skip_serializing_if = "crate::run_output::_helpers::chunks::is_zero" + )] + pub omitted_before: i64, +} + +/// Which way a search looks from its line. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum SearchDirection { + #[default] + Forward, + Backward, +} + +/// A search of a node's output for text, case-insensitively, from a line in one direction. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +pub struct OutputSearchQuery { + pub node: String, + pub stream: Option, + pub text: String, + /// Look from this line, which a forward search includes, as a backward one does. + pub from: Option, + #[param(inline)] + pub direction: Option, +} + +/// The next match; across the whole output, how many match and which this is, when the output was small enough to scan; or where to continue. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct OutputSearch { + pub line: Option, + pub count: Option, + pub rank: Option, + /// `from` for the next search in the same direction, when this one stopped before finding a match. + pub continue_from: Option, +} + +/// A whole node's output to download, both streams or one. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +pub struct OutputDownloadQuery { + pub node: String, + pub stream: Option, +} + +/// A node's lines across both streams, or one stream of them, or the whole run's lines. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct OutputView { + pub(crate) run_id: uuid::Uuid, + pub(crate) node: Option, + pub(crate) stream: Option, +} + +/// A batch ready to index: its chunk's key and sizes, and each segment's place in the chunk. +#[derive(Clone, Debug)] +pub(crate) struct PreparedChunk { + pub(crate) run_id: uuid::Uuid, + pub(crate) claim_id: uuid::Uuid, + pub(crate) batch: u64, + pub(crate) object_key: String, + pub(crate) text_bytes: i64, + pub(crate) stored_bytes: i64, + pub(crate) dropped_bytes: i64, + pub(crate) segments: Vec, +} + +/// One segment of a prepared chunk; its error and warning lines count from 0 within the segment. +#[derive(Clone, Debug)] +pub(crate) struct PreparedSegment { + pub(crate) node_key: String, + pub(crate) stream: OutputStream, + pub(crate) line_count: i64, + pub(crate) text_offset: i64, + pub(crate) text_bytes: i64, + /// Each marked line's offset within the segment, level and text. + pub(crate) marks: Vec<(i64, OutputLevel, String)>, +} + +/// One stored segment of a view, numbered in the view's numbering, with the chunk that holds it. +#[derive(Clone, Debug, Deserialize)] +pub(crate) struct StoredSegment { + pub(crate) first_line: i64, + pub(crate) line_count: i64, + pub(crate) node_key: String, + pub(crate) stream: OutputStream, + pub(crate) text_offset: i64, + pub(crate) text_bytes: i64, + pub(crate) object_key: String, + pub(crate) chunk_text_bytes: i64, + pub(crate) received_at: chrono::DateTime, +} + +/// A node's line count and its marks so far in one stream, before a segment adds to them. +#[derive(Clone, Copy, Debug, Default, Deserialize)] +pub(crate) struct StoredNodeLines { + pub(crate) node_lines: i64, + pub(crate) stream_marks: i64, +} + +/// A run's next chunk number and the bytes kept in its first and last parts. +#[derive(Clone, Copy, Debug, Deserialize)] +pub(crate) struct StoredTotals { + pub(crate) next_chunk: i64, + pub(crate) line_count: i64, + pub(crate) head_bytes: i64, + pub(crate) tail_bytes: i64, +} + +/// The oldest chunk of a capped run's last part, which goes first. +#[derive(Clone, Debug, Deserialize)] +pub(crate) struct TailChunk { + pub(crate) chunk: i64, + pub(crate) text_bytes: i64, + pub(crate) object_key: String, + pub(crate) lines: i64, +} + +/// A worker's run output on its way to the server: lines assembled per node and stream, sent in batches by one thread. +#[derive(Debug)] +pub struct RunOutputUploader { + pub(crate) shared: Arc, + pub(crate) sender: std::sync::Mutex>>, +} + +#[derive(Debug, Default)] +pub(crate) struct UploadShared { + pub(crate) state: std::sync::Mutex, + pub(crate) wake: std::sync::Condvar, +} + +/// What the capture has handed over and the sender has still to send. +#[derive(Debug, Default)] +pub(crate) struct UploadState { + /// The bytes after each node and stream's last newline, keyed by node key, empty outside any node. + pub(crate) partial: std::collections::BTreeMap<(String, OutputStream), Vec>, + pub(crate) segments: Vec, + pub(crate) batch_bytes: usize, + pub(crate) batch_started: Option, + pub(crate) queued: std::collections::VecDeque, + pub(crate) next_batch: u64, + /// Bytes dropped since the last segment, reported on the next one. + pub(crate) unreported_drops: u64, + pub(crate) closing: Option, + pub(crate) summary: UploadSummary, +} + +/// How a worker's run output went: batches stored, bytes it could not send, and why sending stopped. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct UploadSummary { + pub stored_batches: u64, + pub dropped_bytes: u64, + pub failure: Option, +} + +/// A finished run whose output is past its retention. +#[derive(Clone, Copy, Debug, Deserialize)] +pub(crate) struct ExpiredRun { + pub(crate) run_id: uuid::Uuid, +} + +/// One count read from the index. +#[derive(Clone, Copy, Debug, Deserialize)] +pub(crate) struct ViewCount { + pub(crate) count: i64, +} + +/// Where a view's kept tail starts after a size cap, and where its kept head ends. +#[derive(Clone, Copy, Debug, Deserialize)] +pub(crate) struct StoredGap { + pub(crate) first_tail: Option, + pub(crate) after_head: Option, + pub(crate) omitted_lines: Option, +} + +/// Reads a view's lines one at a time in one direction, a batch of segments at a time, each chunk once. +#[derive(Debug)] +pub(crate) struct ViewReader<'a> { + pub(crate) store: &'a crate::store::models::ControlStore, + pub(crate) output: &'a OutputStore, + pub(crate) view: &'a OutputView, + pub(crate) direction: SearchDirection, + /// Forwards, the next line to read; backwards, the line before which to read. + pub(crate) bound: i64, + /// The view's first line after a size cap's gap, and how many lines the gap left out. + pub(crate) gap: Option<(i64, i64)>, + pub(crate) pending: std::collections::VecDeque, + pub(crate) exhausted: bool, + /// The last chunk read, by object key. + pub(crate) cached: Option<(String, Arc)>, + pub(crate) chunks_read: usize, +} + +/// A page's rows as they are read, and the lowest and highest lines they cover. +#[derive(Clone, Debug, Default)] +pub(crate) struct PageRows { + pub(crate) rows: Vec, + pub(crate) low: Option, + pub(crate) high: Option, +} + +/// Lines read so far that are the same but for their numbers, and what they share. +#[derive(Clone, Debug, Default)] +pub(crate) struct SimilarRun { + pub(crate) key: Option, + pub(crate) lines: Vec, +} + +/// A run's line count and what a size cap or a slow worker left out. +#[derive(Clone, Copy, Debug, Default, Deserialize)] +pub(crate) struct StoredOutputTotals { + pub(crate) line_count: i64, + pub(crate) omitted_bytes: i64, + pub(crate) omitted_lines: i64, + pub(crate) dropped_bytes: i64, +} + +/// Which node's error and warning lines the index includes. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::IntoParams)] +#[into_params(parameter_in = Query)] +pub struct OutputIndexQuery { + pub node: Option, +} + +/// A whole search's matches: how many, the first and last, and where they sit around the line searched from. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct SearchTally { + pub(crate) count: i64, + /// Matches before the line searched from, and up to and including it. + pub(crate) before: i64, + pub(crate) through: i64, + pub(crate) first: Option, + pub(crate) last: Option, + /// The first match at or after the line searched from, and the last at or before it. + pub(crate) after: Option, + pub(crate) upto: Option, +} diff --git a/crates/sqlbuild-orchestration/src/run_output/types.rs b/crates/sqlbuild-orchestration/src/run_output/types.rs new file mode 100644 index 0000000000..0c11423b0e --- /dev/null +++ b/crates/sqlbuild-orchestration/src/run_output/types.rs @@ -0,0 +1,8 @@ +//! Shapes run output reads share. + +/// Who reads a run's output: their audit context and person, the run as location, target and ID, and the server's default role. +pub(crate) type PersonRunRead<'a> = ( + (&'a crate::credentials::models::AuditContext, uuid::Uuid), + (uuid::Uuid, &'a str, uuid::Uuid), + crate::credentials::models::DefaultRole, +); diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs index 3d4a0840e8..ecf00c55d8 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs @@ -14,6 +14,7 @@ use crate::runs::_helpers::groups::context::load_group; use crate::runs::_helpers::groups::selection::{failed_upstream, member_dependencies}; use crate::runs::_helpers::lifecycle::claims::reserve_claims; use crate::runs::_helpers::lifecycle::publish_change::publish_change; +use crate::runs::constants::UNFINISHED_NODE_STATUSES; use crate::runs::models::{ ChangingRun, GroupContext, NodeOutcome, QueueCandidate, RunChange, RunChangeRequest, RunNodeRecord, RunOutcome, RunStatus, @@ -158,8 +159,8 @@ async fn skip_blocked_members( let failed_job = failed.request_json.job_key.clone().unwrap_or_default(); let rows; (transaction, rows) = query(transaction, - "SELECT n.node_key, n.skipped_because_of FROM sqb_run_nodes n WHERE n.run_id=$1 AND n.kind='node' \ - AND n.status IN ('failed','skipped','cancelled') ORDER BY CASE n.status WHEN 'failed' THEN 0 ELSE 1 END, n.node_key LIMIT 1", + &format!("SELECT n.node_key, n.skipped_because_of FROM sqb_run_nodes n WHERE n.run_id=$1 AND n.kind='node' \ + AND n.status IN ({UNFINISHED_NODE_STATUSES}) ORDER BY CASE n.status WHEN 'failed' THEN 0 ELSE 1 END, n.node_key LIMIT 1"), vec![Parameter::Id(failed.request_json.run_id)]).await?; let cause: Option = rows.first().and_then(|row| { row["skipped_because_of"] @@ -175,6 +176,8 @@ async fn skip_blocked_members( node_key: node_key.clone(), outcome: NodeOutcome::Skipped, rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: cause.clone(), error_message: None, @@ -237,7 +240,7 @@ async fn finish_group( let rank = |status: &str| match status { "failed" => 5, "cancelled" => 4, - "skipped" => 3, + "skipped" | "not_run" => 3, "warn" => 2, "success" => 1, _ => 0, @@ -269,6 +272,8 @@ async fn finish_group( node_key: key.clone(), outcome, rows_affected: node.rows_affected, + table_rows: node.table_rows, + no_change_reason: node.no_change_reason.clone(), error_code: node.error_code.clone(), skipped_because_of: node.skipped_because_of.clone(), error_message: None, diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/groups/selection.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/groups/selection.rs index 663807fc4d..3f7497793e 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/groups/selection.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/groups/selection.rs @@ -5,6 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::declarations::models::DependencyFailure; use crate::runs::_helpers::groups::context::load_group; use crate::runs::constants::SUPERSEDED_CHILD; +use crate::runs::constants::UNFINISHED_NODE_STATUSES; use crate::runs::models::{GroupContext, GroupRun, QueueWait, RunRequest, RunStatus}; use crate::snapshots::main::reads::read_snapshot_nodes::read_snapshot_nodes; use crate::store::errors::ControlError; @@ -131,7 +132,7 @@ pub(crate) async fn skipped_nodes( } let (transaction, rows) = query(transaction, &format!("SELECT n.node_key, n.status, n.skipped_because_of FROM sqb_run_nodes n JOIN sqb_runs r ON r.run_id=n.run_id \ - WHERE r.parent_run_id=$1 AND r.run_id<>$2 AND n.kind='node' AND n.status IN ('failed','skipped','cancelled') \ + WHERE r.parent_run_id=$1 AND r.run_id<>$2 AND n.kind='node' AND n.status IN ({UNFINISHED_NODE_STATUSES}) \ AND NOT {SUPERSEDED_CHILD}"), vec![Parameter::Id(parent_id), Parameter::Id(request.run_id)]).await?; let failures: BTreeMap = rows diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs index d974cbc37c..adecced069 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs @@ -71,6 +71,8 @@ pub(crate) fn validate_authority( RunChange::CancelRequested { .. } | RunChange::Started | RunChange::NodeStarted { .. } + | RunChange::NodeProgress { .. } + | RunChange::NodeLog { .. } | RunChange::NodeFinished { .. } | RunChange::CheckStarted { .. } | RunChange::CheckFinished { .. } @@ -83,6 +85,8 @@ pub(crate) fn validate_authority( request.change, RunChange::Started | RunChange::NodeStarted { .. } + | RunChange::NodeProgress { .. } + | RunChange::NodeLog { .. } | RunChange::NodeFinished { .. } | RunChange::CheckStarted { .. } | RunChange::CheckFinished { .. } @@ -135,6 +139,8 @@ pub(crate) fn validate_change( state.worker_instance.is_some() && matches!(state.status, Queued | Launched) } RunChange::NodeStarted { .. } + | RunChange::NodeProgress { .. } + | RunChange::NodeLog { .. } | RunChange::NodeFinished { .. } | RunChange::CheckStarted { .. } | RunChange::CheckFinished { .. } @@ -168,7 +174,7 @@ pub(crate) fn validate_change( .unwrap_or_default() }; let good = count("success") + count("warn"); - let bad = count("failed") + count("skipped") + count("cancelled"); + let bad = count("failed") + count("skipped") + count("cancelled") + count("not_run"); let expected = if bad > 0 && good > 0 { RunOutcome::Partial } else if bad > 0 { diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/missing_secrets.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/missing_secrets.rs new file mode 100644 index 0000000000..e6333054dc --- /dev/null +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/missing_secrets.rs @@ -0,0 +1,57 @@ +//! The nodes a run couldn't run for a missing secret say so in its node list, so a page needs no read per failed node. + +use std::collections::BTreeMap; + +use uuid::Uuid; + +use crate::runs::_helpers::lifecycle::error_text::finished_error_message; +use crate::runs::constants::{ + MISSING_SECRET_ERROR_CODE, MISSING_SECRET_PHRASE, MISSING_SECRET_PREFIX, +}; +use crate::runs::models::RunNodeRecord; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{ControlTransaction, Parameter}; + +/// `nodes` with the worker's message on each that failed unstarted for a missing secret; any other error text stays behind view.evidence, and an unreadable fact leaves its node without one. The run's invocation bounds the event join, as PostgreSQL has no index on an event's `storage_id`. +pub(in crate::runs) async fn with_missing_secrets( + transaction: ControlTransaction, + run_id: Uuid, + mut nodes: Vec, +) -> Result<(ControlTransaction, Vec), ControlError> { + let possible: bool = nodes.iter().any(|node| { + node.started_at.is_none() && node.error_code.as_deref() == Some(MISSING_SECRET_ERROR_CODE) + }); + if !possible { + return Ok((transaction, nodes)); + } + let (transaction, rows) = query( + transaction, + "SELECT n.node_key, e.payload FROM sqb_run_nodes n \ + JOIN recall_events e ON e.storage_id=n.finished_storage_id \ + WHERE n.run_id=$1 AND e.invocation_id=$2 AND n.kind='node' AND n.status='failed' \ + AND n.error_code=$3 AND n.started_at IS NULL", + vec![ + Parameter::Id(run_id), + Parameter::Text(format!("scheduler/{run_id}")), + Parameter::Text(MISSING_SECRET_ERROR_CODE.into()), + ], + ) + .await?; + let mut messages: BTreeMap = BTreeMap::new(); + for row in rows { + let (Some(key), Ok(Some(message))) = ( + row["node_key"].as_str(), + finished_error_message(&row["payload"]), + ) else { + continue; + }; + if message.starts_with(MISSING_SECRET_PREFIX) && message.contains(MISSING_SECRET_PHRASE) { + messages.insert(key.to_owned(), message); + } + } + for node in &mut nodes { + node.missing_secret = messages.remove(&node.node_key); + } + Ok((transaction, nodes)) +} diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/mod.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/mod.rs index 17b09a8a93..4df927d688 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/mod.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/mod.rs @@ -4,9 +4,10 @@ pub(in crate::runs) mod checks; pub(in crate::runs) mod claims; pub(crate) mod error_text; pub(in crate::runs) mod events; +pub(in crate::runs) mod missing_secrets; pub(crate) mod narrowing; pub(in crate::runs) mod nodes; -pub(in crate::runs) mod output; +pub(crate) mod output; pub(crate) mod pinned_jobs; pub(in crate::runs) mod projection; pub(crate) mod publications; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/nodes.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/nodes.rs index a41eacfc2d..c8de4ff646 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/nodes.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/nodes.rs @@ -15,19 +15,23 @@ pub(crate) async fn project_node( request: &RunChangeRequest, counts: &BTreeMap, ) -> Result { - let (node, status, rows, error, skipped) = match &request.change { - RunChange::NodeStarted { node_key } => (node_key, NODE_RUNNING, None, None, None), + let (node, status, (rows, table_rows, no_change), error, skipped) = match &request.change { + RunChange::NodeStarted { node_key } => { + (node_key, NODE_RUNNING, (None, None, None), None, None) + } RunChange::NodeFinished { node_key, outcome, rows_affected, + table_rows, + no_change_reason, error_code, skipped_because_of, .. } => ( node_key, outcome.as_str(), - *rows_affected, + (*rows_affected, *table_rows, no_change_reason.clone()), error_code.clone(), skipped_because_of.clone(), ), @@ -68,10 +72,12 @@ pub(crate) async fn project_node( *counts.entry(status.into()).or_default() += 1; let (transaction, _) = query(transaction, "UPDATE sqb_run_nodes SET status=$1, started_at=CASE WHEN $1='running' THEN $2 ELSE started_at END, \ - ended_at=$3, rows_affected=$4, error_code=$5, skipped_because_of=$6 WHERE run_id=$7 AND node_key=$8 AND kind='node'", + ended_at=$3, rows_affected=$4, error_code=$5, skipped_because_of=$6, table_rows=$9, no_change_reason=$10 \ + WHERE run_id=$7 AND node_key=$8 AND kind='node'", vec![Parameter::Text(status.into()), Parameter::Time(now), Parameter::OptionalTime((status != NODE_RUNNING).then_some(now)), - rows.map_or(Parameter::Null(sqlbuild_recall::schema::models::ColumnType::Integer), Parameter::Integer), - Parameter::OptionalText(error), Parameter::OptionalText(skipped), Parameter::Id(request.run_id), Parameter::Text(node.clone())]).await?; + optional_integer(rows), + Parameter::OptionalText(error), Parameter::OptionalText(skipped), Parameter::Id(request.run_id), Parameter::Text(node.clone()), + optional_integer(table_rows), Parameter::OptionalText(no_change)]).await?; let (transaction, _) = query( transaction, "UPDATE sqb_runs SET node_counts_json=$1 WHERE run_id=$2", @@ -83,3 +89,11 @@ pub(crate) async fn project_node( .await?; Ok(transaction) } + +/// `value` as an integer parameter, or an integer-typed NULL. +fn optional_integer(value: Option) -> Parameter { + value.map_or( + Parameter::Null(sqlbuild_recall::schema::models::ColumnType::Integer), + Parameter::Integer, + ) +} diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs index b253195c57..6440fe7d23 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs @@ -4,6 +4,7 @@ use std::collections::BTreeMap; use serde_json::json; +use crate::run_output::constants::NODE_LOG_MESSAGE_BYTES; use crate::runs::_helpers::lifecycle::checks::check_execution_history; use crate::runs::_helpers::lifecycle::nodes::project_node; use crate::runs::models::{ChangingRun, RunChange, RunChangeRequest, RunOutcome}; @@ -63,6 +64,47 @@ pub(crate) async fn project_run_state( RunChange::NodeStarted { .. } | RunChange::NodeFinished { .. } => { return project_node(transaction, request, &state.node_counts_json).await; } + RunChange::NodeLog { + node_key, + level, + message, + } => { + if message.len() > NODE_LOG_MESSAGE_BYTES { + return Err(ControlError::Invalid( + "a ctx.log message is longer than its limit".into(), + )); + } + (transaction, _) = query( + transaction, + "INSERT INTO sqb_run_node_logs (run_id, event_id, node_key, level, message, logged_at) \ + VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (run_id, event_id) DO NOTHING", + vec![ + Parameter::Id(request.run_id), + Parameter::Id(request.event_id), + Parameter::Text(node_key.clone()), + Parameter::Text(level.as_str().into()), + Parameter::Text(message.clone()), + Parameter::Time(now), + ], + ) + .await?; + } + RunChange::NodeProgress { + node_key, + rows_so_far, + } => { + (transaction, _) = query( + transaction, + "UPDATE sqb_run_nodes SET rows_so_far=$1 WHERE run_id=$2 AND node_key=$3 \ + AND kind='node' AND status='running'", + vec![ + Parameter::Integer(*rows_so_far), + Parameter::Id(request.run_id), + Parameter::Text(node_key.clone()), + ], + ) + .await?; + } RunChange::AuditFailuresIgnored { count } => { (transaction, _) = query( transaction, @@ -116,7 +158,7 @@ pub(crate) async fn project_run_state( "UPDATE sqb_run_nodes SET status=CASE WHEN status='running' THEN $1 ELSE $2 END, ended_at=$3 \ WHERE run_id=$4 AND kind='node' AND status IN ('pending','running')", vec![Parameter::Text(if cancelled { "cancelled" } else { "failed" }.into()), - Parameter::Text(if cancelled { "cancelled" } else { "skipped" }.into()), Parameter::Time(now), Parameter::Id(request.run_id)]).await?; + Parameter::Text(if cancelled { "cancelled" } else { "not_run" }.into()), Parameter::Time(now), Parameter::Id(request.run_id)]).await?; let counts; (transaction, counts) = query(transaction, "SELECT status, COUNT(*) AS count FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' GROUP BY status", diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/queued.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/queued.rs index bef39000b3..710f577bd1 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/queued.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/queued.rs @@ -5,6 +5,7 @@ use sqlbuild_recall::records::main::sha256_hex::sha256_hex; use crate::runs::_helpers::requests::permissions::rewrites_history; use crate::runs::models::RunRequest; +use crate::snapshots::main::reads::read_snapshot_nodes::read_snapshot_nodes; use crate::store::errors::ControlError; use crate::store::main::query::query; use crate::store::models::{ControlTransaction, Parameter}; @@ -38,10 +39,19 @@ pub(crate) async fn project_queued_run( Parameter::Text(request.requested_by.clone()), Parameter::Integer(request.priority), Parameter::Json(selection), Parameter::Text(digest), Parameter::Time(now), Parameter::Json(json!({"pending": request.selection.len()})), Parameter::Integer(cursor), Parameter::Json(json!(request)), Parameter::Boolean(rewrites_history(request, std::slice::from_ref(request)))]).await?; + let definitions; + (transaction, definitions) = + read_snapshot_nodes(transaction, request.snapshot_id, Some(&request.selection)).await?; for node in &request.selection { + let materialization: Option = definitions + .get(node) + .and_then(|definition| definition.definition.get("materialization")) + .and_then(serde_json::Value::as_str) + .map(str::to_owned); (transaction, _) = query(transaction, - "INSERT INTO sqb_run_nodes (run_id, node_key, status, writes) VALUES ($1,$2,'pending',$3)", - vec![Parameter::Id(request.run_id), Parameter::Text(node.clone()), Parameter::Boolean(request.write_set.contains(node))]).await?; + "INSERT INTO sqb_run_nodes (run_id, node_key, status, writes, materialization) VALUES ($1,$2,'pending',$3,$4)", + vec![Parameter::Id(request.run_id), Parameter::Text(node.clone()), Parameter::Boolean(request.write_set.contains(node)), + Parameter::OptionalText(materialization)]).await?; } Ok(transaction) } diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs index d0be33c348..ccdf164e8f 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs @@ -2,6 +2,7 @@ use uuid::Uuid; +use crate::runs::_helpers::lifecycle::missing_secrets::with_missing_secrets; use crate::runs::_helpers::lifecycle::waits::queue_states; use crate::runs::models::{RunNodeRecord, RunRecord}; @@ -53,12 +54,14 @@ pub(crate) async fn list_runs_in( Ok((transaction, runs)) } +/// The run's nodes, each with the materialization its snapshot gave it when the run was queued and, when a missing secret stopped it, that message. pub(crate) async fn run_nodes_in( transaction: ControlTransaction, run_id: Uuid, ) -> Result<(ControlTransaction, Vec), ControlError> { - query_records(transaction, - "SELECT node_key, status, started_at, ended_at, rows_affected, error_code, skipped_because_of \ - FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' ORDER BY node_key", - vec![Parameter::Id(run_id)]).await + let (transaction, nodes) = query_records(transaction, + "SELECT node_key, status, started_at, ended_at, rows_affected, table_rows, rows_so_far, no_change_reason, \ + materialization, error_code, skipped_because_of FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' ORDER BY node_key", + vec![Parameter::Id(run_id)]).await?; + with_missing_secrets(transaction, run_id, nodes).await } diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/retries.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/retries.rs index be525c3a86..3b476505a9 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/retries.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/retries.rs @@ -11,8 +11,8 @@ use crate::declarations::main::frozen_definitions::frozen_definitions; use crate::declarations::models::OnFailure; use crate::runs::_helpers::lifecycle::events::append_run_event; use crate::runs::_helpers::requests::rerun::frozen_rerun; -use crate::runs::constants::NODE_FAILED; use crate::runs::constants::{MEMBER_RECOVERED_EVENT, MEMBER_RETRYING_EVENT}; +use crate::runs::constants::{NODE_FAILED, UNFINISHED_NODE_STATUSES}; use crate::runs::main::requests::queue_run::queue_run; use crate::runs::models::{RerunRequest, RunCommand, RunOrigin, RunRequest, RunRetry}; use crate::snapshots::constants::SOURCE_KEY_PREFIX; @@ -30,16 +30,18 @@ pub(crate) enum QueuedRetry { Member, } -/// Rerun the failed and skipped nodes after the policy's delay, unless the run was cancelled, used up its retries, or its retry's ID is already taken. +/// Rerun the unfinished nodes after the policy's delay, unless a cancel of the run was requested, used up its retries, or its retry's ID is already taken. pub(crate) async fn queue_retry( transaction: ControlTransaction, run_id: Uuid, ) -> Result<(ControlTransaction, QueuedRetry), ControlError> { let (transaction, rows) = query( transaction, - "SELECT r.request_json, r.cancel_requested_at, \ - (SELECT COUNT(*) FROM sqb_run_nodes n WHERE n.run_id=r.run_id AND n.kind='node' AND n.status IN ('failed','skipped')) AS retryable \ - FROM sqb_runs r WHERE r.run_id=$1", + &format!( + "SELECT r.request_json, r.cancel_requested_at, \ + (SELECT COUNT(*) FROM sqb_run_nodes n WHERE n.run_id=r.run_id AND n.kind='node' AND n.status IN ({UNFINISHED_NODE_STATUSES})) AS retryable \ + FROM sqb_runs r WHERE r.run_id=$1" + ), vec![Parameter::Id(run_id)], ) .await?; @@ -130,7 +132,7 @@ async fn not_retried( Ok(transaction) } -/// The member's next attempt inside its running group: its failed nodes and those it skipped because of them. +/// The member's next attempt inside its running group: its failed and cancelled nodes and those it skipped because of them. async fn queue_member_retry( transaction: ControlTransaction, source: &RunRequest, @@ -161,8 +163,10 @@ async fn queue_member_retry( } let (transaction, rows) = query( transaction, - "SELECT node_key, status, skipped_because_of FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' \ - AND status IN ('failed','skipped')", + &format!( + "SELECT node_key, status, skipped_because_of FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' \ + AND status IN ({UNFINISHED_NODE_STATUSES})" + ), vec![Parameter::Id(source.run_id)], ) .await?; @@ -203,6 +207,7 @@ async fn queue_member_retry( run_id: retry_id, origin: RunOrigin::Rerun, rerun_of_run_id: Some(source.run_id), + chain_run_id: Some(source.chain_run_id.unwrap_or(source.run_id)), requested_by: "system:retry".into(), selection, write_set, diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs index d23fd5f973..1da450a36e 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs @@ -123,6 +123,7 @@ pub(crate) async fn frozen_publication_request( job_settings: plan.job_settings, retry: None, member_attempt: None, + chain_run_id: None, }, )), )) diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/job.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/job.rs index 32f1728946..2bf28a6318 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/job.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/job.rs @@ -60,6 +60,9 @@ pub(crate) async fn frozen_group_children( rerun_of_run_id: request .rerun_of_run_id .map(|id| Uuid::new_v5(&id, name.as_bytes())), + chain_run_id: request + .chain_run_id + .map(|id| Uuid::new_v5(&id, name.as_bytes())), write_set, selection, settings, diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs index c4f1844a8b..cde7fc7942 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/rerun.rs @@ -1,4 +1,4 @@ -//! Retry immutable execution inputs, narrowing only to durable failed and skipped outcomes or to named nodes of the source run. +//! Retry immutable execution inputs, narrowing only to durable unfinished outcomes or to named nodes of the source run. use std::collections::BTreeSet; @@ -10,6 +10,7 @@ use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::_helpers::lifecycle::pinned_jobs::{build_settings, narrow_pinned_jobs}; use crate::runs::_helpers::requests::permissions::authorize_execution; +use crate::runs::constants::UNFINISHED_NODE_STATUSES; use crate::runs::models::{RerunRequest, RunCommand, RunKind, RunOrigin, RunRequest, RunStatus}; use crate::snapshots::constants::SOURCE_KEY_PREFIX; use crate::snapshots::main::write_sets::job_write_set::job_write_set; @@ -66,7 +67,9 @@ pub(crate) async fn frozen_rerun( let rows; (transaction, rows) = query( transaction, - "SELECT node_key FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' AND status IN ('failed','skipped')", + &format!( + "SELECT node_key FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' AND status IN ({UNFINISHED_NODE_STATUSES})" + ), vec![Parameter::Id(request.source_run_id)], ) .await?; @@ -93,6 +96,7 @@ pub(crate) async fn frozen_rerun( ); } narrow_pinned_jobs(&mut frozen); + frozen.chain_run_id = Some(frozen.chain_run_id.unwrap_or(request.source_run_id)); frozen.run_id = request.run_id; frozen.origin = RunOrigin::Rerun; frozen.parent_run_id = None; @@ -120,7 +124,7 @@ pub(crate) async fn frozen_rerun( } if request.from_failure && frozen.selection.is_empty() { return Err(ControlError::Invalid( - "source run has no failed or skipped nodes".into(), + "source run has no failed, cancelled, skipped or unreached nodes".into(), )); } if frozen.selection.len() != named.len() && !named.is_empty() { diff --git a/crates/sqlbuild-orchestration/src/runs/constants.rs b/crates/sqlbuild-orchestration/src/runs/constants.rs index 585c10a548..3416a41a12 100644 --- a/crates/sqlbuild-orchestration/src/runs/constants.rs +++ b/crates/sqlbuild-orchestration/src/runs/constants.rs @@ -3,6 +3,8 @@ pub(crate) const NODE_PENDING: &str = "pending"; pub(crate) const NODE_RUNNING: &str = "running"; pub(crate) const NODE_FAILED: &str = "failed"; +/// The node states a rerun from failure, an automatic retry and a group treat as unfinished, as a SQL list. +pub(crate) const UNFINISHED_NODE_STATUSES: &str = "'failed','skipped','cancelled','not_run'"; pub(crate) const HEARTBEAT_TIMEOUT_SECONDS: i64 = 45; pub(crate) const MONITOR_BATCH_SIZE: usize = 100; @@ -52,6 +54,8 @@ pub(crate) const VARS_SETTING: &str = "vars"; pub(crate) const SUPERSEDED_CHILD: &str = "EXISTS(SELECT 1 FROM sqb_runs s WHERE s.parent_run_id=r.parent_run_id AND s.rerun_of_run_id=r.run_id)"; /// The group run event recorded when a failed member is queued to run again. pub(crate) const MEMBER_RETRYING_EVENT: &str = "run_member_retrying"; +/// The scheduler's launch fact, which names the container a worker started in, if any. +pub(crate) const RUN_LAUNCHED_EVENT: &str = "run_launched"; /// The group run event recorded when a retried member succeeds. pub(crate) const MEMBER_RECOVERED_EVENT: &str = "run_member_recovered"; @@ -61,3 +65,12 @@ pub(crate) const PUBLICATIONS_PER_TARGET: usize = 2; /// Selected keys per page of a selection evaluation, and the most a request may ask for. pub(crate) const SELECTION_PAGE_DEFAULT: u32 = 1_000; pub(crate) const SELECTION_PAGE_MAX: u32 = 10_000; + +/// A followed run's repeated output reads are audited at most once per person, run and kind in this window, on each server. +pub(crate) const REPEATED_READ_AUDIT: std::time::Duration = std::time::Duration::from_secs(600); + +/// The code a node fails with when its provider is missing secrets. +pub(crate) const MISSING_SECRET_ERROR_CODE: &str = "D012"; +/// How a worker's message for such a node starts, and the phrase after its variables. +pub(crate) const MISSING_SECRET_PREFIX: &str = "provider "; +pub(crate) const MISSING_SECRET_PHRASE: &str = " not set (missing from "; diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs index 404b43a0cc..18ac562fb8 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs @@ -6,4 +6,5 @@ pub mod monitor_runs; pub mod observe_run; pub mod publish_run_output; pub mod publish_run_recall; +pub mod require_active_claim; pub mod run_execution; diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/require_active_claim.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/require_active_claim.rs new file mode 100644 index 0000000000..88e39547ba --- /dev/null +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/require_active_claim.rs @@ -0,0 +1,16 @@ +//! Refuse work under a claim that is no longer the run's active claim. + +use uuid::Uuid; + +use crate::runs::_helpers::lifecycle::output::claim_envelope; +use crate::store::errors::ControlError; +use crate::store::models::ControlTransaction; + +/// An error unless `claim_id` is `run_id`'s active claim. +pub(crate) async fn require_active_claim( + transaction: ControlTransaction, + claim: (Uuid, Uuid), +) -> Result { + let (transaction, _) = claim_envelope(transaction, claim).await?; + Ok(transaction) +} diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/run_execution.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/run_execution.rs index 4cfbd8a8f9..7bc57fb446 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/execution/run_execution.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/run_execution.rs @@ -4,8 +4,11 @@ use std::collections::BTreeMap; use uuid::Uuid; +use crate::discovered_sets::constants::DISCOVERED_DOCUMENT; +use crate::discovered_sets::types::DiscoveredSets; use crate::runs::_helpers::groups::selection::skipped_nodes; use crate::runs::models::{ExecutionMetadata, RunClaim, RunExecution}; +use crate::snapshots::main::reads::read_snapshot_documents::read_snapshot_documents; use crate::store::errors::ControlError; use crate::store::main::begin::begin; use crate::store::main::commit::commit; @@ -46,7 +49,19 @@ pub async fn run_execution( }) .collect::>()?; let (transaction, skipped_nodes) = skipped_nodes(transaction, &metadata.request_json).await?; + let (transaction, mut documents) = read_snapshot_documents( + transaction, + metadata.request_json.snapshot_id, + Some(&[DISCOVERED_DOCUMENT]), + ) + .await?; commit(transaction).await?; + let discovered: DiscoveredSets = documents + .remove(DISCOVERED_DOCUMENT) + .map(serde_json::from_value) + .transpose() + .map_err(|error| ControlError::Invalid(error.to_string()))? + .unwrap_or_default(); Ok(Some(RunExecution { claim: RunClaim { claim_id, @@ -56,5 +71,6 @@ pub async fn run_execution( sqb_version: metadata.sqb_version, node_hashes, skipped_nodes, + discovered, })) } diff --git a/crates/sqlbuild-orchestration/src/runs/main/requests/frozen_job_request.rs b/crates/sqlbuild-orchestration/src/runs/main/requests/frozen_job_request.rs index 458bea0d16..861b34107f 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/requests/frozen_job_request.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/requests/frozen_job_request.rs @@ -107,6 +107,7 @@ pub(crate) async fn frozen_job_request( job_settings: Default::default(), retry: None, member_attempt: None, + chain_run_id: None, }, )) } diff --git a/crates/sqlbuild-orchestration/src/runs/models.rs b/crates/sqlbuild-orchestration/src/runs/models.rs index 8f39f93b48..0e4ed5c66b 100644 --- a/crates/sqlbuild-orchestration/src/runs/models.rs +++ b/crates/sqlbuild-orchestration/src/runs/models.rs @@ -1,5 +1,6 @@ //! Frozen run requests and the run, node and claim records the control store keeps. +use crate::discovered_sets::types::DiscoveredSets; use std::collections::{BTreeMap, BTreeSet}; use chrono::{DateTime, Utc}; @@ -8,6 +9,7 @@ use uuid::Uuid; use crate::credentials::models::Action; use crate::declarations::models::PoolSlots; +use crate::runs::constants::RUN_LAUNCHED_EVENT; use crate::runs::types::{CommandPlanner, PreparedPublication}; use crate::snapshots::models::WriterNode; @@ -181,6 +183,9 @@ pub struct RunRequest { /// Which attempt of its member job a group child is, from the second on; the first leaves it unset. #[serde(default, skip_serializing_if = "Option::is_none")] pub member_attempt: Option, + /// The first run of this run's rerun chain, read as `ctx.root_run_id`; unset for the first run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub chain_run_id: Option, } /// Which retry of the job's `[retry]` policy a run is, and when it may start. @@ -382,6 +387,26 @@ pub struct RunNarrowing { pub exclude: Vec, } +/// The level of a line a node logged with `ctx.log`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum NodeLogLevel { + Info, + Warning, + Error, +} + +impl NodeLogLevel { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Info => "info", + Self::Warning => "warning", + Self::Error => "error", + } + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "snake_case")] pub enum NodeOutcome { @@ -390,6 +415,8 @@ pub enum NodeOutcome { Failed, Skipped, Cancelled, + /// The run stopped before it reached the node: nothing upstream failed or skipped it. + NotRun, } impl NodeOutcome { @@ -401,6 +428,7 @@ impl NodeOutcome { Self::Failed => "failed", Self::Skipped => "skipped", Self::Cancelled => "cancelled", + Self::NotRun => "not_run", } } } @@ -411,8 +439,24 @@ pub struct RunNodeRecord { pub status: String, pub started_at: Option>, pub ended_at: Option>, + /// Rows a statement inserted, merged or deleted, as the warehouse reported them. pub rows_affected: Option, + /// The rows a fully rebuilt table holds, read from the warehouse's metadata where that count is exact. + #[serde(default)] + pub table_rows: Option, + /// Rows written so far while the node runs, from microbatch batches or a loader's progress. + #[serde(default)] + pub rows_so_far: Option, + /// Why a node that ran changed nothing, such as `unchanged since its last build`. + #[serde(default)] + pub no_change_reason: Option, + /// The node's materialization in the run's snapshot, such as `table`, `incremental` or `view`. + #[serde(default)] + pub materialization: Option, pub error_code: Option, + /// For a node that failed unstarted because a provider was missing secrets, its redacted message naming the provider, variables and places looked; never other error text. + #[serde(default)] + pub missing_secret: Option, pub skipped_because_of: Option, } @@ -440,6 +484,15 @@ pub struct RunEventRecord { /// A summary the scheduler writes for a group run's member events, such as a member retry; never error or SQL text. #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, + /// For a check's result: its name as declared, its ID and this result's, and the rows it found; never its SQL or rows. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub check_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub check_binding_key: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub check_result_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub check_rows: Option, } /// One error-severity audit failure a run or one of its current members let through; never its SQL or evidence. @@ -558,6 +611,9 @@ pub struct RunExecution { /// Derived from completed sibling facts and pinned lineage, never a mutable request rewrite. #[serde(default)] pub skipped_nodes: BTreeMap, + /// The discovered sets the run's snapshot saved, which the worker compiles from. + #[schema(value_type = Object)] + pub discovered: DiscoveredSets, } #[derive(Debug, Deserialize)] @@ -609,10 +665,27 @@ pub enum RunChange { NodeStarted { node_key: String, }, + /// Rows a running node has written so far; a worker sends at most one every few seconds per node. + NodeProgress { + node_key: String, + rows_so_far: i64, + }, + /// A line a node logged with `ctx.log`; a worker sends at most a few hundred per node. + NodeLog { + node_key: String, + level: NodeLogLevel, + message: String, + }, NodeFinished { node_key: String, outcome: NodeOutcome, rows_affected: Option, + /// The rows a fully rebuilt table holds, where the warehouse's metadata count is exact. + #[serde(default, skip_serializing_if = "Option::is_none")] + table_rows: Option, + /// Why a node that ran changed nothing. + #[serde(default, skip_serializing_if = "Option::is_none")] + no_change_reason: Option, error_code: Option, skipped_because_of: Option, /// Redacted and bounded on the way in, whoever sends it; absent from older workers. @@ -656,10 +729,12 @@ pub enum RunChange { impl RunChange { pub(crate) const fn event_type(&self) -> &'static str { match self { - Self::Launched { .. } => "run_launched", + Self::Launched { .. } => RUN_LAUNCHED_EVENT, Self::LaunchFailed { .. } => "run_launch_failed", Self::Started => "run_started", Self::NodeStarted { .. } => "run_node_started", + Self::NodeProgress { .. } => "run_node_progress", + Self::NodeLog { .. } => "run_node_log", Self::NodeFinished { .. } => "run_node_finished", Self::CheckStarted { .. } => "run_check_started", Self::CheckFinished { .. } => "run_check_finished", @@ -676,6 +751,8 @@ impl RunChange { pub(crate) fn node_key(&self) -> Option<&str> { match self { Self::NodeStarted { node_key } + | Self::NodeProgress { node_key, .. } + | Self::NodeLog { node_key, .. } | Self::NodeFinished { node_key, .. } | Self::CheckStarted { node_key } | Self::CheckFinished { node_key, .. } => Some(node_key), diff --git a/crates/sqlbuild-orchestration/src/scheduler/_helpers/persistence.rs b/crates/sqlbuild-orchestration/src/scheduler/_helpers/persistence.rs index 50d8784f6e..a07f94a5bc 100644 --- a/crates/sqlbuild-orchestration/src/scheduler/_helpers/persistence.rs +++ b/crates/sqlbuild-orchestration/src/scheduler/_helpers/persistence.rs @@ -73,6 +73,7 @@ pub(crate) async fn persist_ticks( job_settings: Default::default(), retry: None, member_attempt: None, + chain_run_id: None, }; transaction = queue_run(transaction, &request).await?; } diff --git a/crates/sqlbuild-orchestration/src/sensors/_helpers/ticks/mod.rs b/crates/sqlbuild-orchestration/src/sensors/_helpers/ticks/mod.rs index 8f8901fc11..93e145e22c 100644 --- a/crates/sqlbuild-orchestration/src/sensors/_helpers/ticks/mod.rs +++ b/crates/sqlbuild-orchestration/src/sensors/_helpers/ticks/mod.rs @@ -4,4 +4,5 @@ pub(crate) mod facts; pub(crate) mod requests; pub(crate) mod schedule; pub(crate) mod transitions; +pub(crate) mod unreadable; pub(crate) mod work; diff --git a/crates/sqlbuild-orchestration/src/sensors/_helpers/ticks/unreadable.rs b/crates/sqlbuild-orchestration/src/sensors/_helpers/ticks/unreadable.rs new file mode 100644 index 0000000000..daebf9a1ed --- /dev/null +++ b/crates/sqlbuild-orchestration/src/sensors/_helpers/ticks/unreadable.rs @@ -0,0 +1,92 @@ +//! A tick an earlier release recorded in a form that no longer decodes, shown from the columns that always read. + +use std::collections::BTreeMap; + +use uuid::Uuid; + +use crate::sensors::constants::{TICK_HANDLED, TICK_RUNNING, TICK_STARTED, UNREADABLE_TICK}; +use crate::sensors::models::{ + PersonSensorCursor, PersonSensorEvaluation, PersonSensorRunRequest, SensorEvaluationOutcome, + StoredEvaluationEvent, +}; + +/// The ticks newest first, with `events` put on them: an unreadable first phase matters only when no later one reads, a later one always. +pub(crate) fn with_unreadable( + mut checks: BTreeMap, + events: Vec, +) -> Vec { + let requested: &str = SensorEvaluationOutcome::Requested.phase(); + let (first, later): (Vec<_>, Vec<_>) = events + .into_iter() + .partition(|event| event.phase == requested); + for event in first { + checks + .entry(event.evaluation_id) + .or_insert_with(|| unreadable_tick(&event)); + } + for event in later { + let check: &mut PersonSensorEvaluation = checks + .entry(event.evaluation_id) + .or_insert_with(|| unreadable_tick(&event)); + check.unreadable = Some(UNREADABLE_TICK.into()); + check.outcome = match event.phase.as_str() { + "completed" => TICK_HANDLED.into(), + phase => phase.into(), + }; + check.phase = event.phase; + check.finished_at = Some(event.occurred_at); + } + let mut ticks: Vec = checks.into_values().collect(); + ticks.sort_by(|left, right| { + (right.requested_at, right.evaluation_id).cmp(&(left.requested_at, left.evaluation_id)) + }); + ticks +} + +/// What the columns say about a tick; its fingerprint is read on its own when the fact still has one. +fn unreadable_tick(event: &StoredEvaluationEvent) -> PersonSensorEvaluation { + PersonSensorEvaluation { + evaluation_id: event.evaluation_id, + phase: SensorEvaluationOutcome::Requested.phase().into(), + outcome: TICK_RUNNING.into(), + requested_at: event.occurred_at, + finished_at: None, + cursor_before: PersonSensorCursor { + event_storage_id: 0, + custom: None, + }, + cursor_after: None, + event_id: event.subject_event_id.clone(), + event_summary: None, + run_ids: Vec::new(), + skip_reason: None, + failure_code: None, + error: None, + skipped_for: Vec::new(), + abandoned_because: None, + skipped_by: None, + unreadable: Some(UNREADABLE_TICK.into()), + definition_fingerprint: event.fact_json["request"]["definition_fingerprint"] + .as_str() + .unwrap_or_default() + .into(), + } +} + +/// An unreadable completed tick started the runs that the recorded run requests name it for. +pub(crate) fn with_requested_runs( + mut checks: Vec, + requests: &[PersonSensorRunRequest], +) -> Vec { + for check in checks.iter_mut().filter(|check| check.unreadable.is_some()) { + check.run_ids = requests + .iter() + .filter(|request| request.evaluation_id == check.evaluation_id) + .map(|request| request.run_id) + .collect(); + if check.outcome == TICK_HANDLED && !check.run_ids.is_empty() { + check.outcome = TICK_STARTED.into(); + } + } + checks +} diff --git a/crates/sqlbuild-orchestration/src/sensors/constants.rs b/crates/sqlbuild-orchestration/src/sensors/constants.rs index 3beb03b1f2..22a21c18ba 100644 --- a/crates/sqlbuild-orchestration/src/sensors/constants.rs +++ b/crates/sqlbuild-orchestration/src/sensors/constants.rs @@ -25,12 +25,15 @@ pub(crate) const TICK_SKIPPED: &str = "skipped"; pub(crate) const TICK_STARTED: &str = "started"; /// The rows `node_event` reads: started nodes and checks of job runs, not of group runs. pub(crate) const NODE_EVENT_ROWS: &str = " AND n.started_at IS NOT NULL AND r.kind<>'group'"; -/// The rows `check_event` reads: checks, audits and SQL tests of job and job-group runs, including those a run selected, which it records as nodes; ad-hoc runs, such as a worker's `sqb test` or `sqb audit`, are development commands. -pub(crate) const CHECK_EVENT_ROWS: &str = " AND r.kind<>'adhoc' AND (n.kind='check' OR n.node_key LIKE 'audit:%' OR n.node_key LIKE 'sql_test:%' OR n.node_key LIKE 'check:%')"; +/// The rows `check_event` reads: checks, audits and SQL tests of job, job-group and manual build runs, including those a run selected, which it records as nodes; a build's request stores no `command`, and other ad-hoc commands, such as a worker's `sqb test` or `sqb audit`, are development commands. +pub(crate) const CHECK_EVENT_ROWS: &str = " AND (r.kind<>'adhoc' OR r.request_json ->> 'command' IS NULL) AND (n.kind='check' OR n.node_key LIKE 'audit:%' OR n.node_key LIKE 'sql_test:%' OR n.node_key LIKE 'check:%')"; /// The key prefixes of checks, audits and SQL tests, whether a run recorded them as checks or as selected nodes. pub(crate) const CHECK_KEY_PREFIXES: [&str; 3] = ["audit:", "sql_test:", "check:"]; /// The `sqb_run_nodes.kind` of a check a run didn't select. pub(crate) const CHECK_ROW_KIND: &str = "check"; +/// Why a tick an earlier release recorded shows without its details. +pub(crate) const UNREADABLE_TICK: &str = + "this tick was recorded by an earlier SQLBuild release and can't be read"; /// The tick phases a failing streak counts: failed, timed out, or abandoned because the location didn't answer. pub(crate) const FAILING_TICK_PHASES: &str = "(phase IN ('failed','timed_out') OR (phase='abandoned' AND fact_json -> 'outcome' ->> 'reason'='unanswered'))"; /// The longest one call of a sensor's function may take: a running sensor holds its location's other sensors, plans and sync until it returns. diff --git a/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs b/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs index 52bb6c2cc0..0669b0bcf3 100644 --- a/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs +++ b/crates/sqlbuild-orchestration/src/sensors/main/read_person_sensor.rs @@ -9,11 +9,12 @@ use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::authorization::main::decisions::person_holds_target::person_holds_target; use crate::credentials::models::{Action, AuditContext, DefaultRole}; use crate::sensors::_helpers::ticks::facts::definition_fingerprint; +use crate::sensors::_helpers::ticks::unreadable::{with_requested_runs, with_unreadable}; use crate::sensors::main::sensor_failing::sensor_failing; use crate::sensors::models::{ PersonSensorCursor, PersonSensorEvaluation, PersonSensorRunRequest, PersonSensorState, - SensorCursor, SensorEvaluationOutcome, SensorEvent, StoredEvaluationEvent, StoredRunRequest, - StoredSensor, + SensorCursor, SensorEvaluationFact, SensorEvaluationOutcome, SensorEvent, + StoredEvaluationEvent, StoredRunRequest, StoredSensor, }; use crate::sensors::constants::{TICK_HANDLED, TICK_RUNNING, TICK_SKIPPED, TICK_STARTED}; @@ -71,6 +72,20 @@ pub async fn read_person_sensor( .await?; let (transaction, failing) = sensor_failing(transaction, trigger_id).await?; commit(transaction).await?; + let run_requests: Vec = requests + .into_iter() + .map(|request| PersonSensorRunRequest { + run_key: if evidence { + redact_text(&request.run_key) + } else { + String::new() + }, + run_id: request.run_id, + evaluation_id: request.evaluation_id, + queued_at: request.queued_at, + status: request.status, + }) + .collect(); Ok(Some(PersonSensorState { failing, cursor: sensor @@ -78,25 +93,12 @@ pub async fn read_person_sensor( .as_ref() .map(|cursor| shown_cursor(cursor, evidence)), definition_fingerprint: definition_fingerprint(&sensor.definition_json)?, - evaluations, - run_requests: requests - .into_iter() - .map(|request| PersonSensorRunRequest { - run_key: if evidence { - redact_text(&request.run_key) - } else { - String::new() - }, - run_id: request.run_id, - evaluation_id: request.evaluation_id, - queued_at: request.queued_at, - status: request.status, - }) - .collect(), + evaluations: with_requested_runs(evaluations, &run_requests), + run_requests, })) } -/// The newest `limit` ticks, each projected from its recorded phases. +/// The newest `limit` ticks, each projected from its recorded phases; one that no longer decodes loses only its own details. async fn evaluations( transaction: ControlTransaction, (trigger_id, limit): (Uuid, Parameter), @@ -104,15 +106,21 @@ async fn evaluations( ) -> Result<(ControlTransaction, Vec), ControlError> { let (transaction, events): (_, Vec) = query_records( transaction, - "SELECT occurred_at, fact_json FROM sqb_sensor_evaluation_events WHERE trigger_id=$1 \ + "SELECT evaluation_id, phase, occurred_at, subject_event_id, fact_json FROM sqb_sensor_evaluation_events WHERE trigger_id=$1 \ AND evaluation_id IN (SELECT evaluation_id FROM sqb_sensor_evaluation_events \ WHERE trigger_id=$1 AND phase='requested' ORDER BY occurred_at DESC LIMIT $2)", vec![Parameter::Id(trigger_id), limit], ) .await?; let mut checks: BTreeMap = BTreeMap::new(); + let mut unreadable: Vec = Vec::new(); for event in events { - let request = &event.fact_json.request; + let Ok(fact) = serde_json::from_value::(event.fact_json.clone()) + else { + unreadable.push(event); + continue; + }; + let request = &fact.request; let check = checks .entry(request.evaluation_id) .or_insert_with(|| PersonSensorEvaluation { @@ -132,9 +140,10 @@ async fn evaluations( skipped_for: Vec::new(), abandoned_because: None, skipped_by: None, + unreadable: None, definition_fingerprint: request.definition_fingerprint.clone(), }); - let outcome = event.fact_json.outcome; + let outcome = fact.outcome; if outcome == SensorEvaluationOutcome::Requested { continue; } @@ -175,11 +184,7 @@ async fn evaluations( _ => {} } } - let mut checks: Vec = checks.into_values().collect(); - checks.sort_by(|left, right| { - (right.requested_at, right.evaluation_id).cmp(&(left.requested_at, left.evaluation_id)) - }); - Ok((transaction, checks)) + Ok((transaction, with_unreadable(checks, unreadable))) } /// A custom value is what the sensor computed from data it read, so it shows only with view.evidence. diff --git a/crates/sqlbuild-orchestration/src/sensors/main/sensor_failing.rs b/crates/sqlbuild-orchestration/src/sensors/main/sensor_failing.rs index c752f4c49b..48e15a54c1 100644 --- a/crates/sqlbuild-orchestration/src/sensors/main/sensor_failing.rs +++ b/crates/sqlbuild-orchestration/src/sensors/main/sensor_failing.rs @@ -1,16 +1,19 @@ //! A sensor is failing from the first failed, timed-out or unanswered tick after its last good one; other abandoned ticks don't count either way. +use chrono::{DateTime, Utc}; use uuid::Uuid; -use crate::sensors::constants::FAILING_TICK_PHASES; +use crate::sensors::constants::{FAILING_TICK_PHASES, UNREADABLE_TICK}; use crate::sensors::models::{ AbandonReason, SensorEvaluationFact, SensorEvaluationOutcome, SensorEvent, SensorFailing, }; +use crate::sensors::types::StreakEnd; use crate::store::errors::ControlError; use crate::store::main::query::query; use crate::store::models::{ControlTransaction, Parameter}; +use crate::store::types::Row; -/// Since when the sensor's ticks have failed, how many have, and the event and reason of the newest; three indexed reads however long the streak. +/// Since when the sensor's ticks have failed, how many have, and the event and reason of the newest; three indexed reads however long the streak. An end that no longer decodes gives its recorded time and event, and says so. pub(crate) async fn sensor_failing( transaction: ControlTransaction, trigger_id: Uuid, @@ -36,34 +39,53 @@ pub(crate) async fn sensor_failing( if failed_ticks == 0 { return Ok((transaction, None)); } - let mut ends: Vec = Vec::new(); + let mut ends: Vec = Vec::new(); let mut transaction = transaction; for order in ["ASC", "DESC"] { let rows; (transaction, rows) = query( transaction, &format!( - "SELECT fact_json {streak} ORDER BY occurred_at {order}, event_id {order} LIMIT 1" + "SELECT fact_json, occurred_at, subject_event_id {streak} \ + ORDER BY occurred_at {order}, event_id {order} LIMIT 1" ), vec![ Parameter::Id(trigger_id), - Parameter::Time(chrono::DateTime::UNIX_EPOCH), + Parameter::Time(DateTime::UNIX_EPOCH), ], ) .await?; let row = rows .first() .ok_or_else(|| ControlError::Invalid("failing streak changed while read".into()))?; - ends.push( - serde_json::from_value::(row["fact_json"].clone()) - .map_err(|error| ControlError::Invalid(error.to_string()))?, - ); + ends.push(streak_end(row)?); } - let [first, newest] = <[SensorEvaluationFact; 2]>::try_from(ends) + let [first, newest] = <[StreakEnd; 2]>::try_from(ends) .map_err(|_| ControlError::Invalid("failing streak has no ends".into()))?; - let event = newest.request.event.as_ref(); - let reason = matches!( - newest.outcome, + let (since, _) = first; + let (_, (reason, event_id, event_summary)) = newest; + Ok(( + transaction, + Some(SensorFailing { + reason, + since, + failed_ticks: usize::try_from(failed_ticks).unwrap_or(usize::MAX), + event_id, + event_summary, + }), + )) +} + +/// When the tick started, then why it failed, its event and that event's summary; from the columns when its fact no longer decodes. +fn streak_end(row: &Row) -> Result { + let Ok(fact) = serde_json::from_value::(row["fact_json"].clone()) else { + let recorded: DateTime = serde_json::from_value(row["occurred_at"].clone()) + .map_err(|error| ControlError::Invalid(error.to_string()))?; + let event_id: Option = row["subject_event_id"].as_str().map(str::to_owned); + return Ok((recorded, (Some(UNREADABLE_TICK.into()), event_id, None))); + }; + let reason: Option = matches!( + fact.outcome, SensorEvaluationOutcome::Abandoned { reason: AbandonReason::Unanswered } @@ -71,17 +93,16 @@ pub(crate) async fn sensor_failing( .then(|| { format!( "the location didn't answer within {}s", - newest.request.definition.timeout_seconds + fact.request.definition.timeout_seconds ) }); + let event: Option<&SensorEvent> = fact.request.event.as_ref(); Ok(( - transaction, - Some(SensorFailing { + fact.request.requested_at, + ( reason, - since: first.request.requested_at, - failed_ticks: usize::try_from(failed_ticks).unwrap_or(usize::MAX), - event_id: event.map(|event| event.id().to_owned()), - event_summary: event.map(SensorEvent::summary), - }), + event.map(|event| event.id().to_owned()), + event.map(SensorEvent::summary), + ), )) } diff --git a/crates/sqlbuild-orchestration/src/sensors/models.rs b/crates/sqlbuild-orchestration/src/sensors/models.rs index 6c8eeef7f4..13fcda983e 100644 --- a/crates/sqlbuild-orchestration/src/sensors/models.rs +++ b/crates/sqlbuild-orchestration/src/sensors/models.rs @@ -526,6 +526,9 @@ pub struct PersonSensorEvaluation { pub abandoned_because: Option, /// The operator who skipped the tick's event, so the function wasn't called. pub skipped_by: Option, + /// Why the tick's details are missing: an earlier release recorded them in a form this one can't read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unreadable: Option, pub definition_fingerprint: String, } @@ -591,11 +594,14 @@ pub(crate) struct StoredSensor { pub(crate) cursor_json: Option, } -/// One recorded phase of a sensor check. +/// One recorded phase of a sensor check; its columns always read, its fact may be in an earlier release's form. #[derive(Debug, Deserialize)] pub(crate) struct StoredEvaluationEvent { + pub(crate) evaluation_id: Uuid, + pub(crate) phase: String, pub(crate) occurred_at: DateTime, - pub(crate) fact_json: SensorEvaluationFact, + pub(crate) subject_event_id: Option, + pub(crate) fact_json: serde_json::Value, } /// A run key the sensor requested and the run it made. diff --git a/crates/sqlbuild-orchestration/src/sensors/types.rs b/crates/sqlbuild-orchestration/src/sensors/types.rs index e5d94095e5..980fa9cd9c 100644 --- a/crates/sqlbuild-orchestration/src/sensors/types.rs +++ b/crates/sqlbuild-orchestration/src/sensors/types.rs @@ -11,3 +11,9 @@ pub(crate) type SourcePage = ( /// A sensor's newest requested evaluation and its terminal phase (`None` while in flight), or why it no longer decodes. pub(crate) type LastAttempt = Result<(crate::sensors::models::SensorEvaluationFact, Option), String>; + +/// An end of a failing streak: when its tick started, then why it failed, its event and that event's summary. +pub(crate) type StreakEnd = ( + chrono::DateTime, + (Option, Option, Option), +); diff --git a/crates/sqlbuild-orchestration/src/snapshots/constants.rs b/crates/sqlbuild-orchestration/src/snapshots/constants.rs index 4c29142d1c..4b8347da56 100644 --- a/crates/sqlbuild-orchestration/src/snapshots/constants.rs +++ b/crates/sqlbuild-orchestration/src/snapshots/constants.rs @@ -1,5 +1,7 @@ //! Snapshot retention keeps recent publications per location and target, collected in small batches. +use crate::discovered_sets::constants::DISCOVERED_DOCUMENT; + pub(crate) const DEFAULT_SNAPSHOT_RETENTION_COUNT: u16 = 10; pub(crate) const SNAPSHOT_RETENTION_BATCH: usize = 10; pub(crate) const CONTENT_HASH_CHUNK: usize = 500; @@ -11,7 +13,7 @@ pub(crate) const PUBLISH_TIMEOUT_SECONDS: u64 = 300; /// The target's non-secret connection settings, a `ConnectionDetails`. pub const CONNECTION_DOCUMENT: &str = "connection"; /// Snapshot document kinds: per-snapshot metadata that never changes a node hash or node change. -pub(crate) const SNAPSHOT_DOCUMENT_KINDS: [&str; 8] = [ +pub(crate) const SNAPSHOT_DOCUMENT_KINDS: [&str; 9] = [ "jobs", "groups", "triggers", @@ -20,6 +22,7 @@ pub(crate) const SNAPSHOT_DOCUMENT_KINDS: [&str; 8] = [ COLUMNS_DOCUMENT, "providers", CONNECTION_DOCUMENT, + DISCOVERED_DOCUMENT, ]; /// Connection keys that may name the signed-in user, in preference order. pub(crate) const USER_KEYS: [&str; 3] = ["user", "username", "login"]; diff --git a/crates/sqlbuild-orchestration/src/snapshots/main/publication/canonical_json_bytes.rs b/crates/sqlbuild-orchestration/src/snapshots/main/publication/canonical_json_bytes.rs new file mode 100644 index 0000000000..f5db12b950 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/snapshots/main/publication/canonical_json_bytes.rs @@ -0,0 +1,11 @@ +//! The canonical JSON bytes a snapshot hashes: object keys sorted at every depth. + +use serde_json::Value; + +use crate::snapshots::_helpers::content::json_bytes; +use crate::store::errors::ControlError; + +/// `value` serialized with its object keys sorted, as snapshot content addresses hash it. +pub fn canonical_json_bytes(value: &Value) -> Result, ControlError> { + json_bytes(value) +} diff --git a/crates/sqlbuild-orchestration/src/snapshots/main/publication/mod.rs b/crates/sqlbuild-orchestration/src/snapshots/main/publication/mod.rs index 0989adab5e..026da2656c 100644 --- a/crates/sqlbuild-orchestration/src/snapshots/main/publication/mod.rs +++ b/crates/sqlbuild-orchestration/src/snapshots/main/publication/mod.rs @@ -1,4 +1,5 @@ pub(in crate::snapshots) mod _publish_snapshot; +pub mod canonical_json_bytes; pub mod next_remote_generation; pub(crate) mod prune_snapshots; pub(crate) mod publish_development_snapshot; diff --git a/crates/sqlbuild-orchestration/src/store/errors.rs b/crates/sqlbuild-orchestration/src/store/errors.rs index 9bf1555826..e95291e646 100644 --- a/crates/sqlbuild-orchestration/src/store/errors.rs +++ b/crates/sqlbuild-orchestration/src/store/errors.rs @@ -11,6 +11,8 @@ pub enum ControlError { Worker(#[from] tokio::task::JoinError), #[error("control-store filesystem: {0}")] Io(#[from] std::io::Error), + #[error("run output store: {0}")] + OutputStore(#[from] object_store::Error), #[error("invalid control-plane data: {0}")] Invalid(String), #[error("control-plane operation denied: {reason}; decision {decision_id}")] diff --git a/crates/sqlbuild-orchestration/src/store/schema.sql b/crates/sqlbuild-orchestration/src/store/schema.sql index 90aacd3aff..7aa63f518f 100644 --- a/crates/sqlbuild-orchestration/src/store/schema.sql +++ b/crates/sqlbuild-orchestration/src/store/schema.sql @@ -56,7 +56,7 @@ CREATE TABLE sqb_snapshot_sources ( ); CREATE TABLE sqb_snapshot_documents ( snapshot_id {uuid} NOT NULL REFERENCES sqb_snapshots(snapshot_id), - kind TEXT NOT NULL CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection')), + kind TEXT NOT NULL CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection', 'discovered')), document_hash TEXT NOT NULL REFERENCES sqb_documents(document_hash), PRIMARY KEY (snapshot_id, kind) ); @@ -178,7 +178,7 @@ CREATE INDEX sqb_runs_active ON sqb_runs(location_id, target, job_key) WHERE sta CREATE TABLE sqb_run_nodes ( run_id {uuid} NOT NULL REFERENCES sqb_runs(run_id), node_key TEXT NOT NULL, - status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'success', 'warn', 'failed', 'skipped', 'cancelled')), + status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'success', 'warn', 'failed', 'skipped', 'cancelled', 'not_run')), writes BOOLEAN NOT NULL, started_at {time}, ended_at {time}, @@ -187,6 +187,10 @@ CREATE TABLE sqb_run_nodes ( skipped_because_of TEXT, kind TEXT NOT NULL DEFAULT 'node' CHECK (kind IN ('node', 'check')), finished_storage_id BIGINT, + table_rows BIGINT, + rows_so_far BIGINT, + no_change_reason TEXT, + materialization TEXT, PRIMARY KEY (run_id, node_key) ); CREATE INDEX sqb_run_nodes_node ON sqb_run_nodes(node_key, run_id); @@ -194,6 +198,71 @@ CREATE INDEX sqb_run_nodes_finished ON sqb_run_nodes(finished_storage_id) WHERE finished_storage_id IS NOT NULL; CREATE INDEX sqb_run_nodes_decisive ON sqb_run_nodes(node_key, finished_storage_id) WHERE finished_storage_id IS NOT NULL AND status IN ('success', 'failed'); +CREATE TABLE sqb_run_output ( + run_id {uuid} PRIMARY KEY REFERENCES sqb_runs(run_id), + next_chunk BIGINT NOT NULL, + line_count BIGINT NOT NULL, + head_bytes BIGINT NOT NULL, + tail_bytes BIGINT NOT NULL, + stored_bytes BIGINT NOT NULL, + omitted_bytes BIGINT NOT NULL, + omitted_lines BIGINT NOT NULL, + dropped_bytes BIGINT NOT NULL +); +CREATE TABLE sqb_run_output_chunks ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + chunk BIGINT NOT NULL, + claim_id {uuid} NOT NULL, + batch BIGINT NOT NULL, + object_key TEXT NOT NULL, + text_bytes BIGINT NOT NULL, + received_at {time} NOT NULL, + part TEXT NOT NULL CHECK (part IN ('head', 'tail')), + PRIMARY KEY (run_id, chunk), + UNIQUE (run_id, claim_id, batch) +); +CREATE TABLE sqb_run_output_segments ( + run_id {uuid} NOT NULL, + chunk BIGINT NOT NULL, + node_key TEXT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + run_line BIGINT NOT NULL, + node_line BIGINT NOT NULL, + line_count BIGINT NOT NULL, + text_offset BIGINT NOT NULL, + text_bytes BIGINT NOT NULL, + PRIMARY KEY (run_id, run_line), + FOREIGN KEY (run_id, chunk) REFERENCES sqb_run_output_chunks(run_id, chunk) +); +CREATE INDEX sqb_run_output_segments_node ON sqb_run_output_segments(run_id, node_key, node_line); +CREATE INDEX sqb_run_output_segments_chunk ON sqb_run_output_segments(run_id, chunk); +CREATE TABLE sqb_run_output_streams ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + node_key TEXT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + line_count BIGINT NOT NULL, + text_bytes BIGINT NOT NULL, + mark_count BIGINT NOT NULL, + PRIMARY KEY (run_id, node_key, stream) +); +CREATE TABLE sqb_run_output_marks ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + node_key TEXT NOT NULL, + node_line BIGINT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + level TEXT NOT NULL CHECK (level IN ('error', 'warning')), + text TEXT NOT NULL, + PRIMARY KEY (run_id, node_key, node_line) +); +CREATE TABLE sqb_run_node_logs ( + run_id {uuid} NOT NULL REFERENCES sqb_runs(run_id), + event_id {uuid} NOT NULL, + node_key TEXT NOT NULL, + level TEXT NOT NULL CHECK (level IN ('info', 'warning', 'error')), + message TEXT NOT NULL, + logged_at {time} NOT NULL, + PRIMARY KEY (run_id, event_id) +); CREATE TABLE sqb_write_claims ( target TEXT NOT NULL, node_key TEXT NOT NULL, @@ -367,6 +436,24 @@ CREATE TABLE sqb_sessions ( revoked_at {time} ); CREATE INDEX sqb_sessions_person ON sqb_sessions(principal_id); +CREATE TABLE sqb_service_accounts ( + principal_id {uuid} PRIMARY KEY REFERENCES sqb_principals(principal_id), + description TEXT, + created_by TEXT NOT NULL +); +CREATE TABLE sqb_service_account_keys ( + key_id {uuid} PRIMARY KEY, + principal_id {uuid} NOT NULL REFERENCES sqb_principals(principal_id), + secret_hash TEXT NOT NULL UNIQUE, + prefix TEXT NOT NULL, + origin TEXT NOT NULL CHECK (origin IN ('issued', 'imported')), + created_at {time} NOT NULL, + created_by TEXT NOT NULL, + expires_at {time}, + revoked_at {time}, + last_used_at {time} +); +CREATE INDEX sqb_service_account_keys_principal ON sqb_service_account_keys(principal_id); CREATE TABLE sqb_password_login_attempts ( attempt_id {uuid} PRIMARY KEY, identity_key TEXT NOT NULL, diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs index dbae6976c5..d2e6a5a163 100644 --- a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs @@ -40,6 +40,30 @@ pub(crate) const MIGRATIONS: &[StoreMigration] = &[ postgres: include_str!("../sql/0005_sensor_functions.postgres.sql"), step: Some(drop_old_form_sensors), }, + StoreMigration { + name: "node_results", + sqlite: include_str!("../sql/0006_node_results.sqlite.sql"), + postgres: include_str!("../sql/0006_node_results.postgres.sql"), + step: None, + }, + StoreMigration { + name: "run_output", + sqlite: include_str!("../sql/0007_run_output.sqlite.sql"), + postgres: include_str!("../sql/0007_run_output.postgres.sql"), + step: None, + }, + StoreMigration { + name: "discovered_document", + sqlite: include_str!("../sql/0008_discovered_document.sqlite.sql"), + postgres: include_str!("../sql/0008_discovered_document.postgres.sql"), + step: None, + }, + StoreMigration { + name: "service_accounts", + sqlite: include_str!("../sql/0009_service_accounts.sqlite.sql"), + postgres: include_str!("../sql/0009_service_accounts.postgres.sql"), + step: None, + }, ]; /// The schema version a store created by this build has. diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0006_node_results.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0006_node_results.postgres.sql new file mode 100644 index 0000000000..f82d2c88b9 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0006_node_results.postgres.sql @@ -0,0 +1,15 @@ +-- A run's nodes say what each one did: the rows a rebuilt table holds, rows written so far while +-- it runs, and why a node that ran changed nothing. A node the run never reached is `not_run`, +-- apart from a node something upstream skipped. Each node also keeps the materialization its +-- snapshot gave it, so listing a run's nodes reads no snapshot. +ALTER TABLE sqb_run_nodes DROP CONSTRAINT IF EXISTS sqb_run_nodes_status_check; + +ALTER TABLE sqb_run_nodes ADD CONSTRAINT sqb_run_nodes_status_check CHECK (status IN ('pending', 'running', 'success', 'warn', 'failed', 'skipped', 'cancelled', 'not_run')); + +ALTER TABLE sqb_run_nodes ADD COLUMN IF NOT EXISTS table_rows BIGINT; + +ALTER TABLE sqb_run_nodes ADD COLUMN IF NOT EXISTS rows_so_far BIGINT; + +ALTER TABLE sqb_run_nodes ADD COLUMN IF NOT EXISTS no_change_reason TEXT; + +ALTER TABLE sqb_run_nodes ADD COLUMN IF NOT EXISTS materialization TEXT; diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0006_node_results.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0006_node_results.sqlite.sql new file mode 100644 index 0000000000..7722993083 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0006_node_results.sqlite.sql @@ -0,0 +1,34 @@ +-- A run's nodes say what each one did: the rows a rebuilt table holds, rows written so far while +-- it runs, and why a node that ran changed nothing. A node the run never reached is `not_run`, +-- apart from a node something upstream skipped. Each node also keeps the materialization its +-- snapshot gave it, so listing a run's nodes reads no snapshot. +CREATE TABLE sqb_run_nodes_v2 ( + run_id {uuid} NOT NULL REFERENCES sqb_runs(run_id), + node_key TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'success', 'warn', 'failed', 'skipped', 'cancelled', 'not_run')), + writes BOOLEAN NOT NULL, + started_at {time}, + ended_at {time}, + rows_affected BIGINT, + error_code TEXT, + skipped_because_of TEXT, + kind TEXT NOT NULL DEFAULT 'node' CHECK (kind IN ('node', 'check')), + finished_storage_id BIGINT, + table_rows BIGINT, + rows_so_far BIGINT, + no_change_reason TEXT, + materialization TEXT, + PRIMARY KEY (run_id, node_key) +); + +INSERT INTO sqb_run_nodes_v2 (run_id, node_key, status, writes, started_at, ended_at, rows_affected, error_code, skipped_because_of, kind, finished_storage_id) SELECT run_id, node_key, status, writes, started_at, ended_at, rows_affected, error_code, skipped_because_of, kind, finished_storage_id FROM sqb_run_nodes; + +DROP TABLE sqb_run_nodes; + +ALTER TABLE sqb_run_nodes_v2 RENAME TO sqb_run_nodes; + +CREATE INDEX sqb_run_nodes_node ON sqb_run_nodes(node_key, run_id); + +CREATE INDEX sqb_run_nodes_finished ON sqb_run_nodes(finished_storage_id) WHERE finished_storage_id IS NOT NULL; + +CREATE INDEX sqb_run_nodes_decisive ON sqb_run_nodes(node_key, finished_storage_id) WHERE finished_storage_id IS NOT NULL AND status IN ('success', 'failed'); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0007_run_output.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0007_run_output.postgres.sql new file mode 100644 index 0000000000..e7a36fa23b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0007_run_output.postgres.sql @@ -0,0 +1,77 @@ +-- A run's output lives in zstd objects in the output store, one per worker batch, and the control +-- store keeps only their index: each chunk, where each node's lines sit in it, numbered both +-- across the node's two streams and across the whole run, each stream's totals, the node's error +-- and warning lines, and what a size cap left out. Lines a node logs with `ctx.log` are kept as +-- the run's node logs. +CREATE TABLE sqb_run_output ( + run_id {uuid} PRIMARY KEY REFERENCES sqb_runs(run_id), + next_chunk BIGINT NOT NULL, + line_count BIGINT NOT NULL, + head_bytes BIGINT NOT NULL, + tail_bytes BIGINT NOT NULL, + stored_bytes BIGINT NOT NULL, + omitted_bytes BIGINT NOT NULL, + omitted_lines BIGINT NOT NULL, + dropped_bytes BIGINT NOT NULL +); + +CREATE TABLE sqb_run_output_chunks ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + chunk BIGINT NOT NULL, + claim_id {uuid} NOT NULL, + batch BIGINT NOT NULL, + object_key TEXT NOT NULL, + text_bytes BIGINT NOT NULL, + received_at {time} NOT NULL, + part TEXT NOT NULL CHECK (part IN ('head', 'tail')), + PRIMARY KEY (run_id, chunk), + UNIQUE (run_id, claim_id, batch) +); + +CREATE TABLE sqb_run_output_segments ( + run_id {uuid} NOT NULL, + chunk BIGINT NOT NULL, + node_key TEXT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + run_line BIGINT NOT NULL, + node_line BIGINT NOT NULL, + line_count BIGINT NOT NULL, + text_offset BIGINT NOT NULL, + text_bytes BIGINT NOT NULL, + PRIMARY KEY (run_id, run_line), + FOREIGN KEY (run_id, chunk) REFERENCES sqb_run_output_chunks(run_id, chunk) +); + +CREATE INDEX sqb_run_output_segments_node ON sqb_run_output_segments(run_id, node_key, node_line); + +CREATE INDEX sqb_run_output_segments_chunk ON sqb_run_output_segments(run_id, chunk); + +CREATE TABLE sqb_run_output_streams ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + node_key TEXT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + line_count BIGINT NOT NULL, + text_bytes BIGINT NOT NULL, + mark_count BIGINT NOT NULL, + PRIMARY KEY (run_id, node_key, stream) +); + +CREATE TABLE sqb_run_output_marks ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + node_key TEXT NOT NULL, + node_line BIGINT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + level TEXT NOT NULL CHECK (level IN ('error', 'warning')), + text TEXT NOT NULL, + PRIMARY KEY (run_id, node_key, node_line) +); + +CREATE TABLE sqb_run_node_logs ( + run_id {uuid} NOT NULL REFERENCES sqb_runs(run_id), + event_id {uuid} NOT NULL, + node_key TEXT NOT NULL, + level TEXT NOT NULL CHECK (level IN ('info', 'warning', 'error')), + message TEXT NOT NULL, + logged_at {time} NOT NULL, + PRIMARY KEY (run_id, event_id) +); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0007_run_output.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0007_run_output.sqlite.sql new file mode 100644 index 0000000000..e7a36fa23b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0007_run_output.sqlite.sql @@ -0,0 +1,77 @@ +-- A run's output lives in zstd objects in the output store, one per worker batch, and the control +-- store keeps only their index: each chunk, where each node's lines sit in it, numbered both +-- across the node's two streams and across the whole run, each stream's totals, the node's error +-- and warning lines, and what a size cap left out. Lines a node logs with `ctx.log` are kept as +-- the run's node logs. +CREATE TABLE sqb_run_output ( + run_id {uuid} PRIMARY KEY REFERENCES sqb_runs(run_id), + next_chunk BIGINT NOT NULL, + line_count BIGINT NOT NULL, + head_bytes BIGINT NOT NULL, + tail_bytes BIGINT NOT NULL, + stored_bytes BIGINT NOT NULL, + omitted_bytes BIGINT NOT NULL, + omitted_lines BIGINT NOT NULL, + dropped_bytes BIGINT NOT NULL +); + +CREATE TABLE sqb_run_output_chunks ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + chunk BIGINT NOT NULL, + claim_id {uuid} NOT NULL, + batch BIGINT NOT NULL, + object_key TEXT NOT NULL, + text_bytes BIGINT NOT NULL, + received_at {time} NOT NULL, + part TEXT NOT NULL CHECK (part IN ('head', 'tail')), + PRIMARY KEY (run_id, chunk), + UNIQUE (run_id, claim_id, batch) +); + +CREATE TABLE sqb_run_output_segments ( + run_id {uuid} NOT NULL, + chunk BIGINT NOT NULL, + node_key TEXT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + run_line BIGINT NOT NULL, + node_line BIGINT NOT NULL, + line_count BIGINT NOT NULL, + text_offset BIGINT NOT NULL, + text_bytes BIGINT NOT NULL, + PRIMARY KEY (run_id, run_line), + FOREIGN KEY (run_id, chunk) REFERENCES sqb_run_output_chunks(run_id, chunk) +); + +CREATE INDEX sqb_run_output_segments_node ON sqb_run_output_segments(run_id, node_key, node_line); + +CREATE INDEX sqb_run_output_segments_chunk ON sqb_run_output_segments(run_id, chunk); + +CREATE TABLE sqb_run_output_streams ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + node_key TEXT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + line_count BIGINT NOT NULL, + text_bytes BIGINT NOT NULL, + mark_count BIGINT NOT NULL, + PRIMARY KEY (run_id, node_key, stream) +); + +CREATE TABLE sqb_run_output_marks ( + run_id {uuid} NOT NULL REFERENCES sqb_run_output(run_id), + node_key TEXT NOT NULL, + node_line BIGINT NOT NULL, + stream TEXT NOT NULL CHECK (stream IN ('stdout', 'stderr')), + level TEXT NOT NULL CHECK (level IN ('error', 'warning')), + text TEXT NOT NULL, + PRIMARY KEY (run_id, node_key, node_line) +); + +CREATE TABLE sqb_run_node_logs ( + run_id {uuid} NOT NULL REFERENCES sqb_runs(run_id), + event_id {uuid} NOT NULL, + node_key TEXT NOT NULL, + level TEXT NOT NULL CHECK (level IN ('info', 'warning', 'error')), + message TEXT NOT NULL, + logged_at {time} NOT NULL, + PRIMARY KEY (run_id, event_id) +); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0008_discovered_document.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0008_discovered_document.postgres.sql new file mode 100644 index 0000000000..b4bc36a9e5 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0008_discovered_document.postgres.sql @@ -0,0 +1,4 @@ +-- Snapshots keep what each @discover function returned in a new 'discovered' document. +ALTER TABLE sqb_snapshot_documents DROP CONSTRAINT sqb_snapshot_documents_kind_check; + +ALTER TABLE sqb_snapshot_documents ADD CONSTRAINT sqb_snapshot_documents_kind_check CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection', 'discovered')); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0008_discovered_document.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0008_discovered_document.sqlite.sql new file mode 100644 index 0000000000..7f6b5eee2a --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0008_discovered_document.sqlite.sql @@ -0,0 +1,15 @@ +-- Snapshots keep what each @discover function returned in a new 'discovered' document. +CREATE TABLE sqb_snapshot_documents_v2 ( + snapshot_id {uuid} NOT NULL REFERENCES sqb_snapshots(snapshot_id), + kind TEXT NOT NULL CHECK (kind IN ('jobs', 'groups', 'triggers', 'roles', 'lineage', 'columns', 'providers', 'connection', 'discovered')), + document_hash TEXT NOT NULL REFERENCES sqb_documents(document_hash), + PRIMARY KEY (snapshot_id, kind) +); + +INSERT INTO sqb_snapshot_documents_v2 (snapshot_id, kind, document_hash) SELECT snapshot_id, kind, document_hash FROM sqb_snapshot_documents; + +DROP TABLE sqb_snapshot_documents; + +ALTER TABLE sqb_snapshot_documents_v2 RENAME TO sqb_snapshot_documents; + +CREATE INDEX IF NOT EXISTS sqb_snapshot_documents_hash ON sqb_snapshot_documents(document_hash); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0009_service_accounts.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0009_service_accounts.postgres.sql new file mode 100644 index 0000000000..d2a35d10b8 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0009_service_accounts.postgres.sql @@ -0,0 +1,20 @@ +-- Service accounts: principals that call with API keys instead of signing in. A key is stored only +-- as its SHA-256, and its prefix identifies it in lists and the audit log. +CREATE TABLE sqb_service_accounts ( + principal_id {uuid} PRIMARY KEY REFERENCES sqb_principals(principal_id), + description TEXT, + created_by TEXT NOT NULL +); +CREATE TABLE sqb_service_account_keys ( + key_id {uuid} PRIMARY KEY, + principal_id {uuid} NOT NULL REFERENCES sqb_principals(principal_id), + secret_hash TEXT NOT NULL UNIQUE, + prefix TEXT NOT NULL, + origin TEXT NOT NULL CHECK (origin IN ('issued', 'imported')), + created_at {time} NOT NULL, + created_by TEXT NOT NULL, + expires_at {time}, + revoked_at {time}, + last_used_at {time} +); +CREATE INDEX sqb_service_account_keys_principal ON sqb_service_account_keys(principal_id); diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0009_service_accounts.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0009_service_accounts.sqlite.sql new file mode 100644 index 0000000000..d2a35d10b8 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0009_service_accounts.sqlite.sql @@ -0,0 +1,20 @@ +-- Service accounts: principals that call with API keys instead of signing in. A key is stored only +-- as its SHA-256, and its prefix identifies it in lists and the audit log. +CREATE TABLE sqb_service_accounts ( + principal_id {uuid} PRIMARY KEY REFERENCES sqb_principals(principal_id), + description TEXT, + created_by TEXT NOT NULL +); +CREATE TABLE sqb_service_account_keys ( + key_id {uuid} PRIMARY KEY, + principal_id {uuid} NOT NULL REFERENCES sqb_principals(principal_id), + secret_hash TEXT NOT NULL UNIQUE, + prefix TEXT NOT NULL, + origin TEXT NOT NULL CHECK (origin IN ('issued', 'imported')), + created_at {time} NOT NULL, + created_by TEXT NOT NULL, + expires_at {time}, + revoked_at {time}, + last_used_at {time} +); +CREATE INDEX sqb_service_account_keys_principal ON sqb_service_account_keys(principal_id); diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/audit_repeats.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/audit_repeats.rs new file mode 100644 index 0000000000..65d4b3097b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/audit_repeats.rs @@ -0,0 +1,32 @@ +//! A run read a page repeats while it follows a run is audited once per window, not on every poll. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use uuid::Uuid; + +use crate::warehouse_history::types::AuditKey; + +/// When each person last had each kind of read of each run audited, on this server. +static AUDITED: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +/// Whether a read by `actor` of kind `action` of `run_id` needs a new audit row: none within `window`. +pub(crate) fn audit_due((actor, action, run_id): (&str, &str, Uuid), window: Duration) -> bool { + let mut audited = AUDITED.lock().unwrap_or_else(PoisonError::into_inner); + let now = Instant::now(); + audited.retain(|_, at| now.duration_since(*at) < window); + !audited.contains_key(&(actor.to_owned(), action.to_owned(), run_id)) +} + +/// Remember that such a read was audited now. +pub(crate) fn record_audit((actor, action, run_id): (&str, &str, Uuid)) { + AUDITED + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert( + (actor.to_owned(), action.to_owned(), run_id), + Instant::now(), + ); +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs index 60f68fcc8c..ea8740171d 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod audit_repeats; pub(crate) mod checks; pub(crate) mod costs; pub(crate) mod coverage; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs index 76eb02e0fa..d0db00cc04 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs @@ -1,15 +1,19 @@ //! A run's Recall rows: the scheduler invocation and its claimed worker's invocations, with fixed column lists. use std::collections::BTreeSet; +use std::time::Duration; use serde_json::{Value, json}; +use sqlbuild_recall::records::constants::AUDIT_COMPLETED_EVENT; use uuid::Uuid; use crate::authorization::main::decisions::authorize_listing::authorize_listing; use crate::authorization::main::decisions::authorize_person::authorize_person; use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; -use crate::runs::constants::{MEMBER_RECOVERED_EVENT, MEMBER_RETRYING_EVENT, SUPERSEDED_CHILD}; +use crate::runs::constants::{ + MEMBER_RECOVERED_EVENT, MEMBER_RETRYING_EVENT, RUN_LAUNCHED_EVENT, SUPERSEDED_CHILD, +}; use crate::runs::main::listings::run_invocations::run_invocations; use crate::runs::models::{ RunErrorText, RunEventRecord, RunIgnoredAuditFailure, RunOutput, RunOutputLine, @@ -21,6 +25,7 @@ use crate::store::main::query::query; use crate::store::main::{begin::begin, commit::commit}; use crate::store::models::{ControlStore, ControlTransaction, Parameter, TransactionMode}; use crate::store::types::Row; +use crate::warehouse_history::_helpers::audit_repeats::{audit_due, record_audit}; /// Events whose node may be named only in their payload: older node and check events, and audit results. const NODE_EVENTS: &str = "'run_node_started','run_node_finished','run_check_started','run_check_finished','audit_completed'"; @@ -105,18 +110,21 @@ pub(crate) async fn run_read( Ok(Some(result)) } -/// A sensitive run read, authorized for `action` and audited as `audit_action` in the same transaction. +/// A sensitive run read, authorized for `action` each time and audited as `audit_action` in the same transaction, once per `repeat` window when given. pub(crate) async fn sensitive_run_read( store: &ControlStore, credentials: (&AuditContext, Uuid), (run, default_role, action): ((Uuid, &str, Uuid), DefaultRole, Action), - (audit_action, read, details): ( - &str, - impl AsyncFnOnce( - ControlTransaction, - &RunRecallScope, - ) -> Result<(ControlTransaction, T), ControlError>, - impl FnOnce(&T) -> Value, + ((audit_action, read, details), repeat): ( + ( + &str, + impl AsyncFnOnce( + ControlTransaction, + &RunRecallScope, + ) -> Result<(ControlTransaction, T), ControlError>, + impl FnOnce(&T) -> Value, + ), + Option, ), ) -> Result, ControlError> { let Some((transaction, scope, Some((context, permission)))) = @@ -125,18 +133,27 @@ pub(crate) async fn sensitive_run_read( return Ok(None); }; let (transaction, result) = read(transaction, &scope).await?; - let transaction = append_audit( - transaction, - &context, - (Uuid::now_v7(), audit_action), - ( - json!(permission), - json!(null), - json!({"run_id": run.2, "read": details(&result)}), - ), - ) - .await?; + let key = (context.actor.as_str(), audit_action, run.2); + let audited: bool = repeat.is_none_or(|window| audit_due(key, window)); + let transaction = if audited { + append_audit( + transaction, + &context, + (Uuid::now_v7(), audit_action), + ( + json!(permission), + json!(null), + json!({"run_id": run.2, "read": details(&result)}), + ), + ) + .await? + } else { + transaction + }; commit(transaction).await?; + if audited && repeat.is_some() { + record_audit(key); + } Ok(Some(result)) } @@ -233,8 +250,13 @@ pub(crate) async fn run_events_in( |filter: &str, next: usize| { format!("SELECT storage_id, event_id, invocation_id, occurred_at, event_type, severity, producer, resource_id, \ resource_kind, resource_name, resource_attempt_id, statement_id, error_type, error_code, duration_ms, outcome, \ - row_count, affected_rows, CASE WHEN event_type IN ('{MEMBER_RETRYING_EVENT}','{MEMBER_RECOVERED_EVENT}') \ - THEN payload END AS member_payload, {} FROM events WHERE {filter} AND storage_id>${next} ORDER BY storage_id LIMIT ${}", node_columns(), next + 1) + row_count, affected_rows, CASE WHEN event_type IN ('{MEMBER_RETRYING_EVENT}','{MEMBER_RECOVERED_EVENT}','{RUN_LAUNCHED_EVENT}') \ + THEN payload END AS member_payload, \ + CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'audit_name' END AS check_name, \ + CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'binding_key' END AS check_binding_key, \ + CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'result_id' END AS check_result_id, \ + CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN CAST(payload->>'violation_count' AS BIGINT) END AS check_rows, \ + {} FROM events WHERE {filter} AND storage_id>${next} ORDER BY storage_id LIMIT ${}", node_columns(), next + 1) }, vec![ Parameter::Integer(after), @@ -243,7 +265,13 @@ pub(crate) async fn run_events_in( ), |row: &mut Row| { let payload = row.remove("member_payload").unwrap_or(Value::Null); - if let Some(message) = member_message(&payload)? { + let launched = row.get("event_type").and_then(Value::as_str) == Some(RUN_LAUNCHED_EVENT); + let message = if launched { + launch_message(&payload)? + } else { + member_message(&payload)? + }; + if let Some(message) = message { row.insert("message".into(), Value::String(message)); } let node = node_of(row); @@ -312,13 +340,34 @@ pub(crate) fn node_of(row: &Row) -> Option<(String, String)> { /// The scheduler's summary of a member retry or recovery on its group run, from its own payload. fn member_message(payload: &Value) -> Result, ControlError> { - let payload: Value = match payload { - Value::String(text) => serde_json::from_str(text) - .map_err(|error| ControlError::Invalid(format!("member event payload: {error}")))?, - Value::Null => return Ok(None), - other => other.clone(), + Ok(event_payload(payload)?.as_ref().and_then(member_summary)) +} + +/// What a launch started: the container it names, or a worker running as a local process. +fn launch_message(payload: &Value) -> Result, ControlError> { + let Some(payload) = event_payload(payload)? else { + return Ok(None); }; - Ok(member_summary(&payload)) + let container = payload["change"]["change"]["container_id"].as_str(); + Ok(Some( + match container { + Some(_) => "Container started", + None => "Worker started (local process)", + } + .to_owned(), + )) +} + +/// An event payload as JSON, which SQLite stores as text. +fn event_payload(payload: &Value) -> Result, ControlError> { + Ok(match payload { + Value::String(text) => Some( + serde_json::from_str(text) + .map_err(|error| ControlError::Invalid(format!("run event payload: {error}")))?, + ), + Value::Null => None, + other => Some(other.clone()), + }) } /// The summary a member retry or recovery payload names, when it names a member. diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs index 077898f3d8..522a16759f 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs @@ -15,3 +15,4 @@ pub mod read_person_run_node_error; pub mod read_person_run_output; pub mod read_person_run_statement_sql; pub mod read_person_run_statements; +pub mod read_run_evidence; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_output.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_output.rs index ec531d7939..65561c8a37 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_output.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_output.rs @@ -4,6 +4,7 @@ use serde_json::json; use uuid::Uuid; use crate::credentials::models::{Action, AuditContext, DefaultRole}; +use crate::runs::constants::REPEATED_READ_AUDIT; use crate::runs::models::RunOutput; use crate::store::errors::ControlError; use crate::store::models::ControlStore; @@ -20,11 +21,11 @@ pub async fn read_person_run_output( store, credentials, (run, default_role, Action::ViewEvidence), - ( + (( "output.read", run_output_in, |output: &RunOutput| json!({"lines": output.lines.len(), "errors": output.errors.len()}), - ), + ), Some(REPEATED_READ_AUDIT)), ) .await } diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statement_sql.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statement_sql.rs index 16d35ffee3..27b6f7ecb9 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statement_sql.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statement_sql.rs @@ -20,11 +20,11 @@ pub async fn read_person_run_statement_sql( store, credentials, (run, default_role, Action::ViewSql), - ( + (( "sql.read", async |transaction, scope| statement_sql_in(transaction, scope, statement_id).await, |sql: &Option| json!({"statement_id": statement_id, "found": sql.is_some()}), - ), + ), None), ) .await? .flatten()) diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_run_evidence.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_run_evidence.rs new file mode 100644 index 0000000000..c44e84c33e --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/read_run_evidence.rs @@ -0,0 +1,31 @@ +//! A run read that needs an evidence permission, authorized and audited in one transaction (once per `repeat` window when given), for other domains. + +use std::time::Duration; + +use serde_json::Value; +use uuid::Uuid; + +use crate::credentials::models::{Action, AuditContext, DefaultRole}; +use crate::store::errors::ControlError; +use crate::store::models::{ControlStore, ControlTransaction}; +use crate::warehouse_history::_helpers::run_recall::{RunRecallScope, sensitive_run_read}; + +/// `None` when the run is not in the location and target, as `sensitive_run_read` decides. +pub(crate) async fn read_run_evidence( + store: &ControlStore, + credentials: (&AuditContext, Uuid), + run: ((Uuid, &str, Uuid), DefaultRole, Action), + read: ( + ( + &str, + impl AsyncFnOnce( + ControlTransaction, + &RunRecallScope, + ) -> Result<(ControlTransaction, T), ControlError>, + impl FnOnce(&T) -> Value, + ), + Option, + ), +) -> Result, ControlError> { + sensitive_run_read(store, credentials, run, read).await +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs index e87cb64e62..01e47f17a0 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod _helpers; pub mod main; pub mod models; +pub(crate) mod types; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/types.rs b/crates/sqlbuild-orchestration/src/warehouse_history/types.rs new file mode 100644 index 0000000000..7198c245e3 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/types.rs @@ -0,0 +1,4 @@ +//! Shapes shared inside the warehouse-history domain. + +/// Who read, what kind of read, and which run: the key of an audited repeated read. +pub(crate) type AuditKey = (String, String, uuid::Uuid); diff --git a/crates/sqlbuild-orchestration/src/worker/_helpers/client.rs b/crates/sqlbuild-orchestration/src/worker/_helpers/client.rs index 820554a6f9..43dd957eb5 100644 --- a/crates/sqlbuild-orchestration/src/worker/_helpers/client.rs +++ b/crates/sqlbuild-orchestration/src/worker/_helpers/client.rs @@ -98,6 +98,20 @@ impl WorkerClient { .await?) } + /// Send one batch of run output; a retried batch is stored once. + pub async fn publish_output_batch( + &self, + batch: &crate::run_output::models::OutputBatch, + ) -> Result { + client_response( + self.connection + .client + .post(format!("{}output/batches", self.run_url)) + .json(batch), + ) + .await + } + /// Run independently from warehouse execution; cancellation is a cooperative request. pub async fn heartbeat(&self) -> Result { let result: HeartbeatResponse = client_response( diff --git a/crates/sqlbuild-orchestration/src/worker/main/fetch_execution.rs b/crates/sqlbuild-orchestration/src/worker/main/fetch_execution.rs new file mode 100644 index 0000000000..5c6245190b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/worker/main/fetch_execution.rs @@ -0,0 +1,10 @@ +//! The claimed run's execution contract, read before the worker compiles anything. + +use crate::runs::models::RunExecution; +use crate::worker::errors::WorkerError; +use crate::worker::models::WorkerClient; + +/// The execution the server holds for the worker's run and claim, such as its saved discovered sets. +pub async fn fetch_execution(client: &WorkerClient) -> Result { + client.execution().await +} diff --git a/crates/sqlbuild-orchestration/src/worker/main/mod.rs b/crates/sqlbuild-orchestration/src/worker/main/mod.rs index 05f5586133..1b804dd162 100644 --- a/crates/sqlbuild-orchestration/src/worker/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/worker/main/mod.rs @@ -1,2 +1,3 @@ pub mod connect_worker; +pub mod fetch_execution; pub mod start_worker; diff --git a/crates/sqlbuild-orchestration/tests/api/helpers.rs b/crates/sqlbuild-orchestration/tests/api/helpers.rs index 7a71ae6f0b..ec98dc3f81 100644 --- a/crates/sqlbuild-orchestration/tests/api/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/helpers.rs @@ -22,10 +22,20 @@ pub(crate) async fn start_api_with_facts( authentication: ApiAuthentication, facts: crate::api::models::ServerFacts, ) -> TestApi { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + start_api_on(store, "127.0.0.1:0", (authentication, facts)).await +} + +/// An API bound to `bind`, reached over IPv4 loopback. +pub(crate) async fn start_api_on( + store: &ControlStore, + bind: &str, + (authentication, facts): (ApiAuthentication, crate::api::models::ServerFacts), +) -> TestApi { + let listener = tokio::net::TcpListener::bind(bind) .await .expect("isolated API socket"); - let url = format!("http://{}", listener.local_addr().expect("API address")); + let port = listener.local_addr().expect("API address").port(); + let url = format!("http://127.0.0.1:{port}"); let (shutdown, signal) = tokio::sync::oneshot::channel(); let store = store.clone(); let task = tokio::spawn(serve_api( diff --git a/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs b/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs index 266d72c524..4bee076d67 100644 --- a/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/plans/helpers.rs @@ -1,5 +1,6 @@ //! People, requests and counts the plan contract builds on. +use crate::platform::models::LocationWorkScope; use uuid::Uuid; use crate::authorization::main::roles::assign_builtin_role::assign_builtin_role; @@ -82,6 +83,7 @@ pub(crate) async fn register_instance(store: &ControlStore, location: Uuid) -> L let poll = LocationWorkPoll { session_id: Uuid::now_v7(), target: "development".into(), + scope: LocationWorkScope::All, }; report_location_health( store, diff --git a/crates/sqlbuild-orchestration/tests/api/service_accounts/helpers.rs b/crates/sqlbuild-orchestration/tests/api/service_accounts/helpers.rs new file mode 100644 index 0000000000..ee136591f4 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/service_accounts/helpers.rs @@ -0,0 +1,164 @@ +//! Service accounts made by the control-store owner, and keyed requests from any address. + +use reqwest::header::COOKIE; +use reqwest::{Client, RequestBuilder, StatusCode, header}; +use serde_json::{Value, json}; +use uuid::Uuid; + +use crate::authorization::main::service_accounts::create_service_account::create_service_account; +use crate::credentials::models::{ + AuditContext, BuiltinRole, IssuedServiceKey, NewServiceAccount, ServiceAccountAuthority, +}; +use crate::store::main::{begin::begin, commit::commit, query::query}; +use crate::store::models::{ControlStore, Parameter, TransactionMode}; +use crate::store::types::Row; + +/// A Host that names neither the browser origin nor a loopback name, as a caller on the network sends. +pub(crate) const NETWORK_HOST: &str = "10.20.30.40:8000"; + +pub(crate) fn owner() -> AuditContext { + AuditContext { + actor: "local-control-store-owner".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + } +} + +/// A service account `name` with `role`, made by the owner, and its key. +pub(crate) async fn service_account( + store: &ControlStore, + name: &str, + role: BuiltinRole, +) -> IssuedServiceKey { + let request = NewServiceAccount { + name: name.into(), + description: None, + role, + }; + create_service_account( + store, + (&owner(), ServiceAccountAuthority::Owner), + (&request, None), + ) + .await + .expect("service account") +} + +/// A client with no browser headers, as a deploy script is. +pub(crate) fn script() -> Client { + Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .expect("script transport") +} + +/// The status of reading the bootstrap with `key`, and whom it names. +pub(crate) async fn keyed_bootstrap(client: &Client, url: &str, key: &str) -> (StatusCode, String) { + let response = client + .get(format!("{url}/api/control/bootstrap")) + .header(header::HOST, NETWORK_HOST) + .bearer_auth(key) + .send() + .await + .expect("keyed bootstrap"); + let status = response.status(); + let body: Value = response.json().await.unwrap_or(Value::Null); + ( + status, + body["access"]["name"] + .as_str() + .unwrap_or_default() + .to_owned(), + ) +} + +/// Every row of `table`. +pub(crate) async fn rows(store: &ControlStore, table: &str) -> Vec { + let (transaction, rows) = query( + begin(store, TransactionMode::Read).await.expect("read"), + &format!("SELECT * FROM {table}"), + Vec::new(), + ) + .await + .expect("rows"); + commit(transaction).await.expect("finish read"); + rows +} + +/// Ends every rotation overlap of `principal_id` now, as if its time had passed. +pub(crate) async fn end_overlaps(store: &ControlStore, principal_id: Uuid) { + let (transaction, _) = query( + begin(store, TransactionMode::Write).await.expect("write"), + "UPDATE sqb_service_account_keys SET expires_at=$1 WHERE principal_id=$2 AND expires_at IS NOT NULL", + vec![ + Parameter::Time(chrono::Utc::now() - chrono::Duration::seconds(1)), + Parameter::Id(principal_id), + ], + ) + .await + .expect("end overlaps"); + commit(transaction).await.expect("commit"); +} + +/// A signed-in person's write: their session cookie and its CSRF token. +pub(crate) async fn person_post( + client: &Client, + (url, path): (&str, &str), + person: &(String, String), + body: &Value, +) -> (StatusCode, Value) { + let response = client + .post(format!("{url}{path}")) + .header(COOKIE, &person.0) + .header("x-sqb-csrf", &person.1) + .json(body) + .send() + .await + .expect("write"); + let status = response.status(); + (status, response.json().await.unwrap_or(Value::Null)) +} + +/// A signed-in person's read. +pub(crate) async fn person_get( + client: &Client, + (url, path): (&str, &str), + person: &(String, String), +) -> (StatusCode, Value) { + let response = client + .get(format!("{url}{path}")) + .header(COOKIE, &person.0) + .send() + .await + .expect("read"); + let status = response.status(); + (status, response.json().await.unwrap_or(Value::Null)) +} + +/// Whether the audit page has an entry by service account `name` with `action`. +pub(crate) fn audited(audit: &Value, (name, action): (&str, &str)) -> bool { + audit.as_array().into_iter().flatten().any(|event| { + event["actor_name"] == json!(name) + && event["actor_kind"] == json!("service") + && event["action"] == json!(action) + }) +} + +pub(crate) fn with_key(request: RequestBuilder, key: &str) -> RequestBuilder { + request.bearer_auth(key) +} + +pub(crate) fn without_key(request: RequestBuilder, _key: &str) -> RequestBuilder { + request +} + +pub(crate) fn no_sign_in() -> crate::api::models::HumanLogin { + crate::api::models::HumanLogin::None +} + +pub(crate) fn password_sign_in() -> crate::api::models::HumanLogin { + crate::api::models::HumanLogin::Password( + crate::api::tests::password_people_helpers::ORIGIN_URL.into(), + ) +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs index 3e84d64d5a..b4ff0f78fe 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_contracts.rs @@ -36,6 +36,8 @@ mod plans_helpers; mod proxy_provisioning_helpers; #[path = "recall/helpers.rs"] mod recall_helpers; +#[path = "service_accounts/helpers.rs"] +mod service_accounts_helpers; #[path = "state_history/helpers.rs"] mod state_history_helpers; #[path = "statistics/eligibility/helpers.rs"] @@ -70,6 +72,8 @@ mod test_custom_roles; mod test_denials; #[path = "test_development.rs"] mod test_development; +#[path = "test_development_hosts.rs"] +mod test_development_hosts; #[path = "test_external_sessions.rs"] mod test_external_sessions; #[path = "test_ingestion_turns.rs"] @@ -114,12 +118,16 @@ mod test_proxy_provisioning; mod test_publish_encoding; #[path = "test_reads.rs"] mod test_reads; +#[path = "test_republish.rs"] +mod test_republish; #[path = "test_resource_costs.rs"] mod test_resource_costs; #[path = "test_run_ids.rs"] mod test_run_ids; #[path = "test_server_errors.rs"] mod test_server_errors; +#[path = "test_service_accounts.rs"] +mod test_service_accounts; #[path = "test_state_history_retention.rs"] mod test_state_history_retention; #[path = "test_statistics_recovery.rs"] diff --git a/crates/sqlbuild-orchestration/tests/api/test_development.rs b/crates/sqlbuild-orchestration/tests/api/test_development.rs index f873c54819..7ab8399d0f 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_development.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_development.rs @@ -126,6 +126,8 @@ fn given_development_when_defaults_publish_then_identity_audit_and_trigger_pause target: "development".into(), triggers: false, principal_id: person, + allowed_hosts: Vec::new(), + listens_beyond_loopback: false, }), ..ApiAuthentication::default() }, diff --git a/crates/sqlbuild-orchestration/tests/api/test_development_hosts.rs b/crates/sqlbuild-orchestration/tests/api/test_development_hosts.rs new file mode 100644 index 0000000000..d0aede2996 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/test_development_hosts.rs @@ -0,0 +1,322 @@ +//! A development server takes only local and opted-in names, and leaves loopback only when asked. + +use reqwest::{StatusCode, header}; +use uuid::Uuid; + +use crate::api::main::serve_api::serve_api; +use crate::api::models::{ApiAuthentication, DevelopmentScope, HumanLogin, ServerFacts}; +use crate::credentials::main::identities::development_person::development_person; +use crate::credentials::models::AuditContext; +use crate::runs::tests::test_types::ExactKeyPlanner; +use crate::store::main::migrate_store::migrate_store; + +use crate::api::tests::helpers::{start_api_on, stop_api}; +use crate::api::tests::test_types::{DevelopmentHostTestCase, DevelopmentListenerTestCase}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_development_server_when_a_request_names_a_host_and_origin_then_only_local_and_allowed_names_pass() + { + let test_cases = [ + DevelopmentHostTestCase { + description: "no opt-in takes loopback", + bind: "127.0.0.1:0", + allowed: &[], + host: "127.0.0.1:{port}", + origin: Some("http://127.0.0.1:{port}"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "no opt-in takes localhost", + bind: "127.0.0.1:0", + allowed: &[], + host: "localhost:{port}", + origin: None, + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "no opt-in refuses a public Host", + bind: "127.0.0.1:0", + allowed: &[], + host: "control.example.com", + origin: None, + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "no opt-in refuses a public Origin", + bind: "127.0.0.1:0", + allowed: &[], + host: "127.0.0.1:{port}", + origin: Some("https://control.example.com"), + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "an allowed name through an HTTPS proxy", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com", + origin: Some("https://control.example.com"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "an allowed name through an HTTP proxy", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com", + origin: Some("http://control.example.com"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "a proxy that writes the default port", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com:443", + origin: Some("https://control.example.com"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "a proxy that rewrites Host only", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "127.0.0.1:{port}", + origin: Some("https://control.example.com"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "an allowed name on the listener port", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com:{port}", + origin: Some("http://control.example.com:{port}"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "names match in any case", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "Control.Example.COM", + origin: None, + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "a rebound name stays refused", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "rebound.example.net:{port}", + origin: None, + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "another site stays refused", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com", + origin: Some("https://other.example.net"), + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "a name that extends an allowed one stays refused", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com.example.net", + origin: None, + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "another port of an allowed name stays refused", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com", + origin: Some("http://control.example.com:9000"), + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "a null Origin stays refused", + bind: "127.0.0.1:0", + allowed: &["control.example.com"], + host: "control.example.com", + origin: Some("null"), + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "a named port", + bind: "127.0.0.1:0", + allowed: &["control.example.com:8443"], + host: "control.example.com:8443", + origin: Some("https://control.example.com:8443"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "a named port is the only one", + bind: "127.0.0.1:0", + allowed: &["control.example.com:8443"], + host: "control.example.com", + origin: None, + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "a named HTTPS port is left out by browsers", + bind: "127.0.0.1:0", + allowed: &["control.example.com:443"], + host: "control.example.com", + origin: Some("https://control.example.com"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "a named HTTPS port is not the HTTP one", + bind: "127.0.0.1:0", + allowed: &["control.example.com:443"], + host: "control.example.com", + origin: Some("http://control.example.com"), + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "an IPv6 name", + bind: "127.0.0.1:0", + allowed: &["[fd00::5]"], + host: "[fd00::5]:{port}", + origin: Some("http://[fd00::5]:{port}"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "an open listener takes loopback", + bind: "0.0.0.0:0", + allowed: &[], + host: "127.0.0.1:{port}", + origin: Some("http://127.0.0.1:{port}"), + expected_status: StatusCode::OK, + }, + DevelopmentHostTestCase { + description: "an open listener refuses its wildcard as a name", + bind: "0.0.0.0:0", + allowed: &[], + host: "0.0.0.0:{port}", + origin: None, + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "an open listener refuses an unlisted name", + bind: "0.0.0.0:0", + allowed: &[], + host: "control.example.com:{port}", + origin: None, + expected_status: StatusCode::FORBIDDEN, + }, + DevelopmentHostTestCase { + description: "an open listener takes an allowed address", + bind: "0.0.0.0:0", + allowed: &["192.0.2.10"], + host: "192.0.2.10:{port}", + origin: Some("http://192.0.2.10:{port}"), + expected_status: StatusCode::OK, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let context = AuditContext { + actor: "local-development".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let scope = DevelopmentScope { + location_id: Uuid::now_v7(), + target: "development".into(), + triggers: false, + principal_id: development_person(store, &context).await.expect("person"), + allowed_hosts: test_case.allowed.iter().map(ToString::to_string).collect(), + listens_beyond_loopback: true, + }; + let authentication = ApiAuthentication { + login: HumanLogin::Development(scope), + ..ApiAuthentication::default() + }; + let api = start_api_on( + store, + test_case.bind, + (authentication, ServerFacts::default()), + ) + .await; + let (_, port) = api.url.rsplit_once(':').expect("port"); + let headers: header::HeaderMap = [ + (header::HOST, Some(test_case.host)), + (header::ORIGIN, test_case.origin), + ] + .into_iter() + .filter_map(|(name, value)| { + value.map(|value| (name, value.replace("{port}", port).parse().expect("header"))) + }) + .collect(); + let response = reqwest::Client::new() + .get(format!("{}/api/control/bootstrap", api.url)) + .headers(headers) + .send() + .await + .expect("request"); + assert_eq!( + response.status(), + test_case.expected_status, + "{}", + test_case.description + ); + drop(response); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_no_opt_in_when_a_development_server_would_listen_beyond_loopback_then_it_refuses_to_start() +{ + let test_cases = [DevelopmentListenerTestCase { + description: "every interface without the opt-in", + bind: "0.0.0.0:0", + expected_refusal: "disabled authentication requires a loopback listener", + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + migrate_store(&fixture.store).await.expect("migrate"); + let listener = tokio::net::TcpListener::bind(test_case.bind) + .await + .expect("listener"); + let refused = serve_api( + fixture.store.clone(), + listener, + ( + ApiAuthentication { + login: HumanLogin::Development(DevelopmentScope { + location_id: Uuid::now_v7(), + target: "development".into(), + triggers: false, + principal_id: Uuid::now_v7(), + allowed_hosts: Vec::new(), + listens_beyond_loopback: false, + }), + ..ApiAuthentication::default() + }, + (Vec::new(), std::sync::Arc::new(ExactKeyPlanner)), + ServerFacts::default(), + ), + (|| {}, async {}), + ) + .await + .expect_err("no opt-in"); + assert!( + refused.to_string().contains(test_case.expected_refusal), + "{}: {refused}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_location_work.rs b/crates/sqlbuild-orchestration/tests/api/test_location_work.rs index 8ccd1afb05..bae56b95a1 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_location_work.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_location_work.rs @@ -5,6 +5,7 @@ use crate::platform::main::health::report_location_health::report_location_healt use crate::platform::main::work::connect_location_work::connect_location_work; use crate::platform::main::work::location_work::location_work; use crate::platform::main::work::request_location_work::request_location_work; +use crate::platform::models::LocationWorkScope; use crate::platform::models::{ LocationHealth, LocationHealthReport, LocationWork, LocationWorkOutcome, LocationWorkPoll, LocationWorkRecord, LocationWorkRequest, LocationWorkResult, @@ -143,6 +144,7 @@ fn given_outbound_work_when_claimed_retried_or_replaced_then_scope_and_immutable let poll = LocationWorkPoll { session_id: Uuid::now_v7(), target: request.target.clone(), + scope: LocationWorkScope::All, }; assert!(worker.poll(&poll).await.is_err(), "register before polling"); for session_id in [poll.session_id, Uuid::nil()] { diff --git a/crates/sqlbuild-orchestration/tests/api/test_password_people.rs b/crates/sqlbuild-orchestration/tests/api/test_password_people.rs index b48ca23f6d..a283735432 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_password_people.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_password_people.rs @@ -140,6 +140,8 @@ fn given_sign_in_without_passwords_when_adding_a_person_then_the_server_has_no_s target: "development".into(), triggers: false, principal_id, + allowed_hosts: Vec::new(), + listens_beyond_loopback: false, }) }, expected_status: StatusCode::NOT_FOUND, diff --git a/crates/sqlbuild-orchestration/tests/api/test_republish.rs b/crates/sqlbuild-orchestration/tests/api/test_republish.rs new file mode 100644 index 0000000000..714721403c --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/test_republish.rs @@ -0,0 +1,273 @@ +//! A republish needs its permission, names who asked, reports its publish and reads its sets back. + +use std::collections::BTreeMap; + +use serde_json::json; +use uuid::Uuid; + +use crate::api::tests::plans_helpers::{person, register_instance}; +use crate::api::tests::test_types::{RepublishTestCase, republish_failed, republish_published}; +use crate::authorization::main::people::bootstrap_user::bootstrap_user; +use crate::credentials::models::{AuditContext, BuiltinRole, DefaultRole}; +use crate::credentials::tests::location_helpers::create_location; +use crate::platform::main::person_reads::read_person_discovered::read_person_discovered; +use crate::platform::main::work::{ + claim_location_work::claim_location_work, complete_location_work::complete_location_work, + read_republish::read_republish, request_location_work::request_location_work, + request_republish::request_republish, +}; +use crate::platform::models::{ + LocationWork, LocationWorkOutcome, LocationWorkRequest, LocationWorkResult, LocationWorkScope, + PersonWorkRequest, RepublishState, +}; +use crate::runs::tests::helpers::snapshot; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::errors::ControlError; +use crate::store::main::{ + begin::begin, commit::commit, migrate_store::migrate_store, query::query, +}; +use crate::store::models::TransactionMode; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_republish_when_requested_claimed_and_completed_then_it_is_authorized_audited_and_read_back() + { + let test_cases = [ + RepublishTestCase { + description: "SQLite republish that published", + backend: Backend::Sqlite, + publishes: true, + outcome: republish_published, + expected_state: RepublishState::Published, + expected_error: None, + }, + RepublishTestCase { + description: "SQLite republish that failed", + backend: Backend::Sqlite, + publishes: false, + outcome: republish_failed, + expected_state: RepublishState::Failed, + expected_error: Some("orders does not parse"), + }, + RepublishTestCase { + description: "PostgreSQL republish that published", + backend: Backend::Postgres, + publishes: true, + outcome: republish_published, + expected_state: RepublishState::Published, + expected_error: None, + }, + RepublishTestCase { + description: "PostgreSQL republish that failed", + backend: Backend::Postgres, + publishes: false, + outcome: republish_failed, + expected_state: RepublishState::Failed, + expected_error: Some("orders does not parse"), + }, + ]; + for test_case in test_cases { + run(async { + let fixture = open_test_store(test_case.backend).await.expect("store"); + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let context = AuditContext { + actor: "control-store-owner".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let admin = bootstrap_user(store, &context, "orders-admin") + .await + .expect("admin"); + let location = create_location(store, "orders", "test-owner") + .await + .expect("location"); + let mut input = snapshot(location); + publish_snapshot(store, &input).await.expect("publish"); + let viewer = person( + store, + (&context, admin), + ("orders-viewer", location), + &[BuiltinRole::Viewer], + ) + .await; + let operator = person( + store, + (&context, admin), + ("orders-deploy", location), + &[BuiltinRole::Operator], + ) + .await; + let asked = PersonWorkRequest { + request_id: Uuid::now_v7(), + reason: "deploy 0.58.0".into(), + }; + let ids = (location, "development", asked.request_id); + + assert!( + matches!( + request_republish( + store, + (&context, Some(viewer)), + (location, "development"), + &asked + ) + .await, + Err(ControlError::Denied { .. }) + ), + "{}: a viewer may not republish", + test_case.description + ); + let connection = LocationWorkRequest { + request_id: Uuid::now_v7(), + location_id: location, + target: "development".into(), + reason: "Check orders connectivity".into(), + work: LocationWork::CheckConnection {}, + }; + request_location_work(store, (&context, None), &connection) + .await + .expect("older work"); + assert!( + request_republish( + store, + (&context, Some(operator)), + (location, "development"), + &asked + ) + .await + .expect("request"), + "{}: an operator may republish", + test_case.description + ); + assert!( + !request_republish( + store, + (&context, Some(operator)), + (location, "development"), + &asked + ) + .await + .expect("retry"), + "{}: a retried request queues nothing", + test_case.description + ); + assert!( + matches!( + read_republish(store, (&context, Some(viewer)), ids, 0).await, + Err(ControlError::Denied { .. }) + ), + "{}: a viewer may not read a republish", + test_case.description + ); + let mut poll = register_instance(store, location).await; + poll.scope = LocationWorkScope::RepublishOnly; + let claim = claim_location_work(store, location, &poll) + .await + .expect("poll") + .expect("claim"); + assert_eq!( + claim.request.work, + LocationWork::Republish { + requested_by: "orders-deploy".into() + }, + "{}: a failing location takes the republish ahead of older work, naming the caller", + test_case.description + ); + let foreign = LocationWorkResult { + claim_id: claim.claim_id, + session_id: poll.session_id, + outcome: LocationWorkOutcome::Published { + snapshot_id: Uuid::now_v7(), + generation: 2, + }, + }; + assert!( + complete_location_work(store, (location, asked.request_id), &foreign) + .await + .is_err(), + "{}: only this target's snapshot counts as published", + test_case.description + ); + input.generation = 2; + input.documents.insert( + "discovered".into(), + json!({"orders_plan": {"status": "ok", "digest": "d-2", + "result": {"items": [{"id": "load", "depends_on": [], "args": {}}], "tags": {"release": "0.58.0"}}}}), + ); + let published = publish_snapshot(store, &input).await.expect("republish"); + let outcome = (test_case.outcome)(published.snapshot_id); + complete_location_work( + store, + (location, asked.request_id), + &LocationWorkResult { outcome, ..foreign }, + ) + .await + .expect("complete"); + let status = read_republish(store, (&context, Some(operator)), ids, 5) + .await + .expect("read") + .expect("status"); + assert_eq!( + ( + status.state, + status.error.as_deref(), + status.snapshot_id.is_some() + ), + ( + test_case.expected_state, + test_case.expected_error, + test_case.publishes + ), + "{}", + test_case.description + ); + let readback = read_person_discovered( + store, + (&context, viewer), + (location, "development"), + DefaultRole::None, + ) + .await + .expect("a viewer reads the sets back") + .expect("published"); + let expected_tags: BTreeMap = + [("release".to_owned(), json!("0.58.0"))].into(); + assert_eq!( + ( + readback.generation, + readback.sets[0].items, + &readback.sets[0].tags + ), + (2, 1, &expected_tags), + "{}: the readback shows the new tags", + test_case.description + ); + let (transaction, audit) = query( + begin(store, TransactionMode::Read).await.expect("read audit"), + "SELECT actor, after_json FROM sqb_security_audit WHERE action='location.work_requested' ORDER BY storage_id DESC LIMIT 1", + vec![], + ) + .await + .expect("audit"); + commit(transaction).await.expect("commit"); + assert_eq!( + ( + &audit[0]["actor"], + &audit[0]["after_json"]["work"]["requested_by"], + &audit[0]["after_json"]["reason"] + ), + ( + &json!(format!("principal:{operator}")), + &json!("orders-deploy"), + &json!("deploy 0.58.0") + ), + "{}: the event names the caller and the reason", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_service_accounts.rs b/crates/sqlbuild-orchestration/tests/api/test_service_accounts.rs new file mode 100644 index 0000000000..8091993648 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/api/test_service_accounts.rs @@ -0,0 +1,1031 @@ +//! Service accounts call with a key on any address; only its hash is kept, and it acts under its own name. + +use std::collections::{BTreeMap, BTreeSet}; + +use reqwest::StatusCode; +use reqwest::header::HOST; +use serde_json::{Value, json}; + +use crate::api::models::{ + ApiAuthentication, HumanLogin, TrustedProxyAuthentication, UnknownProxyUsers, +}; +use crate::api::tests::helpers::{start_api_with_authentication, stop_api}; +use crate::api::tests::password_people_helpers::{ + ORIGIN_URL, PASSWORD, browser, password_administrator, password_person, session, +}; +use crate::api::tests::service_accounts_helpers::{ + NETWORK_HOST, audited, end_overlaps, keyed_bootstrap, no_sign_in, owner, password_sign_in, + person_get, person_post, rows, script, service_account, with_key, without_key, +}; +use crate::api::tests::test_types::{ + ImportedKeyAcceptedTestCase, ImportedKeyTestCase, KeyOnlyTestCase, KeyedRoleTestCase, + LoginModeTestCase, PersonImportTestCase, ProxyBindingTestCase, ProxyKeyTestCase, + ServiceAccountLifecycleTestCase, ServiceAccountPermissionTestCase, ServiceAccountRoleTestCase, +}; +use crate::authorization::_helpers::administrator_roles::assign_role_in; +use crate::authorization::main::roles::grant_admin::grant_admin; +use crate::authorization::main::service_accounts::create_service_account::create_service_account; +use crate::credentials::_helpers::service_keys::key_hash; +use crate::credentials::main::identities::create_principal::create_principal; +use crate::credentials::models::{ + BuiltinRole, NewServiceAccount, RoleAssignmentRequest, RoleKey, ServiceAccountAuthority, +}; +use crate::store::main::{begin::begin, migrate_store::migrate_store}; +use crate::store::models::TransactionMode; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_service_account_when_its_key_is_used_rotated_and_disabled_then_only_working_keys_authenticate() + { + let test_cases = [ + ServiceAccountLifecycleTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_key_length: 45, + expected_overlap_keys: 2, + }, + ServiceAccountLifecycleTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_key_length: 45, + expected_overlap_keys: 2, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + password_administrator(store, "ada").await; + let api = start_api_with_authentication( + store, + ApiAuthentication { + login: HumanLogin::Password(ORIGIN_URL.into()), + ..ApiAuthentication::default() + }, + ) + .await; + let (client, keyed) = (browser(), script()); + let url = api.url.as_str(); + let ada = session(&client, url, "ada").await; + + let (status, issued) = person_post( + &client, + (url, "/api/admin/service-accounts"), + &ada, + &json!({"name": "orders-deploy", "description": "Release pipeline", "role": "developer"}), + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "{}: create {issued}", + test_case.description + ); + let key = issued["key"].as_str().expect("key").to_owned(); + let id = issued["account"]["principal_id"] + .as_str() + .expect("id") + .to_owned(); + assert_eq!( + (key.starts_with("sqbk_"), key.len()), + (true, test_case.expected_key_length), + "{}: key shape", + test_case.description + ); + assert_eq!( + ( + &issued["account"]["keys"][0]["prefix"], + &issued["account"]["role"] + ), + (&json!(key[..11]), &json!("developer")), + "{}: prefix and role", + test_case.description + ); + let (_, listed) = person_get(&client, (url, "/api/admin/service-accounts"), &ada).await; + assert!( + listed.to_string().contains("orders-deploy") && !listed.to_string().contains(&key), + "{}: listed without its key", + test_case.description + ); + let stored = rows(store, "sqb_service_account_keys").await; + assert_eq!( + stored[0]["secret_hash"], + json!(key_hash(&key)), + "{}: only the hash is stored", + test_case.description + ); + for table in [ + "sqb_service_account_keys", + "sqb_service_accounts", + "sqb_principals", + "sqb_security_audit", + ] { + let text = serde_json::to_string(&rows(store, table).await).expect("rows"); + assert!( + !text.contains(&key[5..]), + "{}: {table} keeps no key", + test_case.description + ); + } + let (_, people) = person_get(&client, (url, "/api/admin/people"), &ada).await; + assert!( + !people.to_string().contains("orders-deploy"), + "{}: not listed as a person", + test_case.description + ); + + assert_eq!( + keyed_bootstrap(&keyed, url, &key).await, + (StatusCode::OK, "orders-deploy".to_owned()), + "{}: a keyed request from any address", + test_case.description + ); + let session_read = keyed + .get(format!("{url}/api/auth/session")) + .header(HOST, NETWORK_HOST) + .bearer_auth(&key) + .send() + .await + .expect("session read"); + let foreign_login = keyed + .post(format!("{url}/api/auth/password/login")) + .header(HOST, NETWORK_HOST) + .bearer_auth(&key) + .json(&json!({"username": "ada", "password": PASSWORD})) + .send() + .await + .expect("login under a foreign host"); + assert_eq!( + (session_read.status(), foreign_login.status()), + (StatusCode::UNAUTHORIZED, StatusCode::UNAUTHORIZED), + "{}: no session, and a key doesn't lift sign-in's host check", + test_case.description + ); + + let ops = service_account(store, "ops-bot", BuiltinRole::Admin).await; + let added = keyed + .post(format!("{url}/api/admin/service-accounts")) + .header(HOST, NETWORK_HOST) + .bearer_auth(&ops.key) + .json(&json!({"name": "report-export", "role": "viewer"})) + .send() + .await + .expect("keyed create"); + let refused = keyed + .get(format!("{url}/api/admin/service-accounts")) + .header(HOST, NETWORK_HOST) + .bearer_auth(&key) + .send() + .await + .expect("keyed refusal"); + assert_eq!( + (added.status(), refused.status()), + (StatusCode::OK, StatusCode::FORBIDDEN), + "{}: keyed calls follow the account's role", + test_case.description + ); + let (_, audit) = person_get(&client, (url, "/api/control/audit?limit=100"), &ada).await; + assert!( + audited(&audit, ("ops-bot", "service_account.created")) + && audited(&audit, ("orders-deploy", "authorization.denied")), + "{}: its actions and refusals are audited under its name", + test_case.description + ); + + let keys = format!("/api/admin/service-accounts/{id}/keys"); + let (status, rotated) = + person_post(&client, (url, &keys), &ada, &json!({"overlap_minutes": 60})).await; + let second = rotated["key"].as_str().expect("new key").to_owned(); + assert_eq!( + (status, rotated["account"]["keys"].as_array().map(Vec::len)), + (StatusCode::OK, Some(test_case.expected_overlap_keys)), + "{}: rotation with an overlap", + test_case.description + ); + assert_eq!( + ( + keyed_bootstrap(&keyed, url, &key).await.0, + keyed_bootstrap(&keyed, url, &second).await.0 + ), + (StatusCode::OK, StatusCode::OK), + "{}: both keys work during the overlap", + test_case.description + ); + end_overlaps(store, uuid::Uuid::parse_str(&id).expect("uuid")).await; + let (_, audit) = person_get(&client, (url, "/api/control/audit?limit=100"), &ada).await; + assert_eq!( + ( + keyed_bootstrap(&keyed, url, &key).await.0, + keyed_bootstrap(&keyed, url, &second).await.0 + ), + (StatusCode::UNAUTHORIZED, StatusCode::OK), + "{}: the old key stops when the overlap ends", + test_case.description + ); + let (_, audit_after) = + person_get(&client, (url, "/api/control/audit?limit=100"), &ada).await; + assert!( + !audited(&audit, ("orders-deploy", "service_account.key_refused")) + && audited( + &audit_after, + ("orders-deploy", "service_account.key_refused") + ), + "{}: a known key refused is audited under its account", + test_case.description + ); + + let (_, rotated) = person_post( + &client, + (url, &keys), + &ada, + &json!({"overlap_minutes": null}), + ) + .await; + let third = rotated["key"].as_str().expect("third key").to_owned(); + let disabled = format!("/api/admin/service-accounts/{id}/disabled"); + let after_rotation = keyed_bootstrap(&keyed, url, &second).await.0; + person_post(&client, (url, &disabled), &ada, &json!({"disabled": true})).await; + let while_disabled = keyed_bootstrap(&keyed, url, &third).await.0; + person_post(&client, (url, &disabled), &ada, &json!({"disabled": false})).await; + let once_enabled = keyed_bootstrap(&keyed, url, &third).await.0; + assert_eq!( + (after_rotation, while_disabled, once_enabled), + ( + StatusCode::UNAUTHORIZED, + StatusCode::UNAUTHORIZED, + StatusCode::OK + ), + "{}: no overlap stops the old key; disabling stops every key until enabled", + test_case.description + ); + + let (_, listed) = person_get(&client, (url, "/api/admin/service-accounts"), &ada).await; + let account = listed + .as_array() + .into_iter() + .flatten() + .find(|a| a["name"] == json!("orders-deploy")) + .cloned() + .unwrap_or(Value::Null); + let key_id = account["keys"][0]["key_id"].as_str().expect("key id"); + let revoke = format!("/api/admin/service-accounts/{id}/keys/{key_id}/revoke"); + let (status, after) = person_post(&client, (url, &revoke), &ada, &Value::Null).await; + assert_eq!( + ( + account["last_used_at"].is_string(), + status, + after["keys"].as_array().map(Vec::len), + keyed_bootstrap(&keyed, url, &third).await.0 + ), + (true, StatusCode::OK, Some(0), StatusCode::UNAUTHORIZED), + "{}: last use recorded, and a key can be stopped outright", + test_case.description + ); + + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_people_with_built_in_roles_when_they_manage_service_accounts_then_only_administrators_can() +{ + let test_cases = [ + ServiceAccountPermissionTestCase { + description: "an administrator lists and adds", + role: BuiltinRole::Admin, + expected_list: StatusCode::OK, + expected_create: StatusCode::OK, + }, + ServiceAccountPermissionTestCase { + description: "a developer is refused both", + role: BuiltinRole::Developer, + expected_list: StatusCode::FORBIDDEN, + expected_create: StatusCode::FORBIDDEN, + }, + ServiceAccountPermissionTestCase { + description: "a viewer is refused both", + role: BuiltinRole::Viewer, + expected_list: StatusCode::FORBIDDEN, + expected_create: StatusCode::FORBIDDEN, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + password_administrator(store, "ada").await; + let person = password_person(store, "sam").await; + let role = RoleAssignmentRequest { + principal_id: person, + role: RoleKey::Builtin(test_case.role), + location_id: None, + target: None, + revoke: false, + }; + assign_role_in( + begin(store, TransactionMode::Write).await.expect("write"), + &owner(), + &role, + ) + .await + .expect("role"); + let api = start_api_with_authentication( + store, + ApiAuthentication { + login: HumanLogin::Password(ORIGIN_URL.into()), + ..ApiAuthentication::default() + }, + ) + .await; + let client = browser(); + let sam = session(&client, &api.url, "sam").await; + let (list, _) = + person_get(&client, (&api.url, "/api/admin/service-accounts"), &sam).await; + let (create, _) = person_post( + &client, + (&api.url, "/api/admin/service-accounts"), + &sam, + &json!({"name": "ci-runner", "role": "operator"}), + ) + .await; + assert_eq!( + (list, create), + (test_case.expected_list, test_case.expected_create), + "{}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_chosen_key_that_breaks_the_import_rules_when_the_owner_imports_it_then_it_is_refused() { + let test_cases = [ + ImportedKeyTestCase { + description: "a key of 31 characters after the prefix is refused", + key: "sqbk_0123456789abcdefghijABCDEFGHIJK", + expected_error: "at least 32 characters", + }, + ImportedKeyTestCase { + description: "a key without the prefix is refused", + key: "0123456789abcdefghijABCDEFGHIJKLMNOPQRSTUV", + expected_error: "must start with sqbk_", + }, + ImportedKeyTestCase { + description: "a key with a space is refused", + key: "sqbk_0123456789abcdefghij ABCDEFGHIJKLMNOP", + expected_error: "without spaces", + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let request = NewServiceAccount { + name: "orders-deploy".into(), + description: None, + role: BuiltinRole::Viewer, + }; + let refused = create_service_account( + store, + (&owner(), ServiceAccountAuthority::Owner), + (&request, Some(test_case.key)), + ) + .await + .map(|issued| issued.account.name); + let error = refused.map_err(|error| error.to_string()); + assert_eq!( + ( + error + .as_ref() + .err() + .is_some_and(|text| text.contains(test_case.expected_error)), + rows(store, "sqb_service_accounts").await.len() + ), + (true, 0), + "{}: {error:?}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_chosen_key_of_at_least_32_characters_when_the_owner_imports_it_then_it_works() { + let test_cases = [ImportedKeyAcceptedTestCase { + description: "a key of 32 characters after the prefix", + key: "sqbk_0123456789abcdefghijABCDEFGHIJKL", + expected_origin: "imported", + expected_status: StatusCode::OK, + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let request = NewServiceAccount { + name: "orders-deploy".into(), + description: None, + role: BuiltinRole::Viewer, + }; + let issued = create_service_account( + store, + (&owner(), ServiceAccountAuthority::Owner), + (&request, Some(test_case.key)), + ) + .await + .expect("imported"); + let api = start_api_with_authentication(store, ApiAuthentication::default()).await; + assert_eq!( + ( + issued.key.as_str(), + serde_json::to_value(issued.account.keys[0].origin).expect("origin"), + keyed_bootstrap(&script(), &api.url, test_case.key).await.0 + ), + ( + test_case.key, + json!(test_case.expected_origin), + test_case.expected_status + ), + "{}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_person_when_they_offer_a_chosen_key_then_only_the_cli_may_import_one() { + let test_cases = [PersonImportTestCase { + description: "a person's request with a chosen key", + expected_error: "only be imported with the CLI", + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let person = create_principal(store, &owner(), "ada") + .await + .expect("person"); + let request = NewServiceAccount { + name: "ci-runner".into(), + description: None, + role: BuiltinRole::Viewer, + }; + let refused = create_service_account( + store, + (&owner(), ServiceAccountAuthority::Person(person)), + (&request, Some("sqbk_0123456789abcdefghijABCDEFGHIJKLMNOP")), + ) + .await; + assert!( + refused.is_err_and(|error| error.to_string().contains(test_case.expected_error)), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_trusted_proxy_when_a_request_carries_the_identity_header_then_only_proxy_peers_are_trusted_and_a_key_wins() + { + let test_cases = [ + ProxyKeyTestCase { + description: "a direct request with the identity header is not trusted", + trusted_peer: "192.0.2.10", + authorize: without_key, + expected_status: StatusCode::UNAUTHORIZED, + expected_name: "", + }, + ProxyKeyTestCase { + description: "a direct keyed request is its service account, whatever the header says", + trusted_peer: "192.0.2.10", + authorize: with_key, + expected_status: StatusCode::OK, + expected_name: "orders-deploy", + }, + ProxyKeyTestCase { + description: "the proxy's request is the person it names", + trusted_peer: "::ffff:127.0.0.1", + authorize: without_key, + expected_status: StatusCode::OK, + expected_name: "ada", + }, + ProxyKeyTestCase { + description: "a keyed request through the proxy is still the service account", + trusted_peer: "::ffff:127.0.0.1", + authorize: with_key, + expected_status: StatusCode::OK, + expected_name: "orders-deploy", + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let ada = create_principal(store, &owner(), "ada") + .await + .expect("person"); + let deploy = service_account(store, "orders-deploy", BuiltinRole::Developer).await; + let api = start_api_with_authentication( + store, + ApiAuthentication { + login: HumanLogin::TrustedProxy(TrustedProxyAuthentication { + allowed_hosts: Vec::new(), + origin: ORIGIN_URL.into(), + trusted_peers: BTreeSet::from([test_case + .trusted_peer + .parse() + .expect("peer")]), + identities: BTreeMap::from([("ada".into(), ada)]), + username_header: "X-SQB-User".into(), + display_name_header: None, + email_header: None, + unknown_users: UnknownProxyUsers::Reject, + proxy_logout_url: None, + }), + ..ApiAuthentication::default() + }, + ) + .await; + let request = script() + .get(format!("{}/api/control/bootstrap", api.url)) + .header(HOST, "control.example.com") + .header("x-sqb-user", "ada"); + let response = (test_case.authorize)(request, &deploy.key) + .send() + .await + .expect("request"); + let status = response.status(); + let body: Value = response.json().await.unwrap_or(Value::Null); + assert_eq!( + (status, body["access"]["name"].as_str().unwrap_or_default()), + (test_case.expected_status, test_case.expected_name), + "{}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_proxy_binding_to_a_service_account_when_the_proxy_names_it_then_it_never_signs_in() { + let test_cases = [ProxyBindingTestCase { + description: "a trusted proxy names a username bound to a service account", + expected_status: StatusCode::UNAUTHORIZED, + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let deploy = service_account(store, "orders-deploy", BuiltinRole::Developer).await; + let api = start_api_with_authentication( + store, + ApiAuthentication { + login: HumanLogin::TrustedProxy(TrustedProxyAuthentication { + allowed_hosts: Vec::new(), + origin: ORIGIN_URL.into(), + trusted_peers: BTreeSet::from(["::ffff:127.0.0.1".parse().expect("peer")]), + identities: BTreeMap::from([( + "deploy".into(), + deploy.account.principal_id, + )]), + username_header: "X-SQB-User".into(), + display_name_header: None, + email_header: None, + unknown_users: UnknownProxyUsers::Reject, + proxy_logout_url: None, + }), + ..ApiAuthentication::default() + }, + ) + .await; + let response = script() + .get(format!("{}/api/control/bootstrap", api.url)) + .header(HOST, "control.example.com") + .header("x-sqb-user", "deploy") + .send() + .await + .expect("request"); + assert_eq!( + response.status(), + test_case.expected_status, + "{}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_server_without_sign_in_when_person_routes_are_called_then_only_service_keys_get_in() { + let test_cases = [ + KeyOnlyTestCase { + description: "a keyed request is its service account", + authorize: with_key, + expected_status: StatusCode::OK, + expected_cache_control: "no-store", + }, + KeyOnlyTestCase { + description: "a request without a key is refused", + authorize: without_key, + expected_status: StatusCode::UNAUTHORIZED, + expected_cache_control: "no-store", + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let deploy = service_account(store, "orders-deploy", BuiltinRole::Viewer).await; + let api = start_api_with_authentication(store, ApiAuthentication::default()).await; + let request = script() + .get(format!("{}/api/control/bootstrap", api.url)) + .header(HOST, NETWORK_HOST); + let response = (test_case.authorize)(request, &deploy.key) + .send() + .await + .expect("request"); + assert_eq!( + ( + response.status(), + response + .headers() + .get("cache-control") + .and_then(|v| v.to_str().ok()) + ), + ( + test_case.expected_status, + Some(test_case.expected_cache_control) + ), + "{}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_service_account_when_its_key_manages_accounts_or_roles_then_its_role_decides_as_for_a_person() + { + let test_cases = [ + KeyedRoleTestCase { + description: "an admin key may add a service account", + role: BuiltinRole::Admin, + path: "/api/admin/service-accounts", + body: r#"{"name": "report-export", "role": "admin"}"#, + expected_status: StatusCode::OK, + expected_denials: 0, + }, + KeyedRoleTestCase { + description: "an admin key may rotate a service account's key", + role: BuiltinRole::Admin, + path: "/api/admin/service-accounts/{target}/keys", + body: r#"{"overlap_minutes": 60}"#, + expected_status: StatusCode::OK, + expected_denials: 0, + }, + KeyedRoleTestCase { + description: "an admin key may stop a service account's key", + role: BuiltinRole::Admin, + path: "/api/admin/service-accounts/{target}/keys/{key}/revoke", + body: r#"null"#, + expected_status: StatusCode::OK, + expected_denials: 0, + }, + KeyedRoleTestCase { + description: "an admin key may disable a service account", + role: BuiltinRole::Admin, + path: "/api/admin/service-accounts/{target}/disabled", + body: r#"{"disabled": true}"#, + expected_status: StatusCode::OK, + expected_denials: 0, + }, + KeyedRoleTestCase { + description: "an admin key may change a service account's role", + role: BuiltinRole::Admin, + path: "/api/admin/service-accounts/{target}/role", + body: r#"{"role": "admin"}"#, + expected_status: StatusCode::OK, + expected_denials: 0, + }, + KeyedRoleTestCase { + description: "an admin key may give a person a role", + role: BuiltinRole::Admin, + path: "/api/admin/roles", + body: r#"{"principal_id": "{person}", "role": "developer", "location_id": null, "target": null, "revoke": false}"#, + expected_status: StatusCode::OK, + expected_denials: 0, + }, + KeyedRoleTestCase { + description: "an admin key may make a person an admin", + role: BuiltinRole::Admin, + path: "/api/admin/people/{person}", + body: r#""grant""#, + expected_status: StatusCode::OK, + expected_denials: 0, + }, + KeyedRoleTestCase { + description: "a developer key may not add a service account", + role: BuiltinRole::Developer, + path: "/api/admin/service-accounts", + body: r#"{"name": "report-export", "role": "admin"}"#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "a developer key may not rotate a service account's key", + role: BuiltinRole::Developer, + path: "/api/admin/service-accounts/{target}/keys", + body: r#"{"overlap_minutes": 60}"#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "a developer key may not stop a service account's key", + role: BuiltinRole::Developer, + path: "/api/admin/service-accounts/{target}/keys/{key}/revoke", + body: r#"null"#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "a developer key may not disable a service account", + role: BuiltinRole::Developer, + path: "/api/admin/service-accounts/{target}/disabled", + body: r#"{"disabled": true}"#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "a developer key may not change a service account's role", + role: BuiltinRole::Developer, + path: "/api/admin/service-accounts/{target}/role", + body: r#"{"role": "admin"}"#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "a developer key may not give a person a role", + role: BuiltinRole::Developer, + path: "/api/admin/roles", + body: r#"{"principal_id": "{person}", "role": "developer", "location_id": null, "target": null, "revoke": false}"#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "a developer key may not make a person an admin", + role: BuiltinRole::Developer, + path: "/api/admin/people/{person}", + body: r#""grant""#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "an admin key may not revoke the last person admin", + role: BuiltinRole::Admin, + path: "/api/admin/people/{sole_admin}", + body: r#""revoke""#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "an admin key may not disable the last person admin", + role: BuiltinRole::Admin, + path: "/api/admin/people/{sole_admin}", + body: r#""disable""#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + KeyedRoleTestCase { + description: "an admin key may not take the last person admin role away", + role: BuiltinRole::Admin, + path: "/api/admin/roles", + body: r#"{"principal_id": "{sole_admin}", "role": "admin", "location_id": null, "target": null, "revoke": true}"#, + expected_status: StatusCode::FORBIDDEN, + expected_denials: 1, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let sole_admin = create_principal(store, &owner(), "ada") + .await + .expect("person"); + grant_admin(store, &owner(), sole_admin) + .await + .expect("administrator"); + let person = password_person(store, "sam").await; + let caller = service_account(store, "ops-bot", test_case.role).await; + let target = service_account(store, "orders-deploy", BuiltinRole::Viewer).await; + let fill = |text: &str| { + text.replace("{target}", &target.account.principal_id.to_string()) + .replace("{key}", &target.account.keys[0].key_id.to_string()) + .replace("{person}", &person.to_string()) + .replace("{sole_admin}", &sole_admin.to_string()) + }; + let api = start_api_with_authentication(store, ApiAuthentication::default()).await; + let body: Value = serde_json::from_str(&fill(test_case.body)).expect("body"); + let response = script() + .post(format!("{}{}", api.url, fill(test_case.path))) + .header(HOST, NETWORK_HOST) + .bearer_auth(&caller.key) + .json(&body) + .send() + .await + .expect("keyed change"); + let status = response.status(); + let text = response.text().await.unwrap_or_default(); + let denials = rows(store, "sqb_security_audit") + .await + .into_iter() + .filter(|row| row["action"] == json!("authorization.denied")) + .count(); + assert_eq!( + (status, denials), + (test_case.expected_status, test_case.expected_denials), + "{}: {text}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_service_account_role_change_when_it_applies_then_the_new_role_replaces_the_old_in_one_change() + { + let test_cases = [ + ServiceAccountRoleTestCase { + description: "admin to viewer on SQLite", + backend: Backend::Sqlite, + from: BuiltinRole::Admin, + to: "viewer", + expected_roles: &["viewer"], + }, + ServiceAccountRoleTestCase { + description: "admin to viewer on PostgreSQL", + backend: Backend::Postgres, + from: BuiltinRole::Admin, + to: "viewer", + expected_roles: &["viewer"], + }, + ServiceAccountRoleTestCase { + description: "viewer to admin on PostgreSQL", + backend: Backend::Postgres, + from: BuiltinRole::Viewer, + to: "admin", + expected_roles: &["admin"], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + password_administrator(store, "ada").await; + let deploy = service_account(store, "orders-deploy", test_case.from).await; + let api = start_api_with_authentication( + store, + ApiAuthentication { + login: HumanLogin::Password(ORIGIN_URL.into()), + ..ApiAuthentication::default() + }, + ) + .await; + let client = browser(); + let ada = session(&client, &api.url, "ada").await; + let path = format!( + "/api/admin/service-accounts/{}/role", + deploy.account.principal_id + ); + let (status, account) = person_post( + &client, + (&api.url, &path), + &ada, + &json!({"role": test_case.to}), + ) + .await; + let mut held: Vec = rows(store, "sqb_role_assignments") + .await + .into_iter() + .filter(|row| row["principal_id"] == json!(deploy.account.principal_id.to_string())) + .filter_map(|row| row["role_key"].as_str().map(str::to_owned)) + .collect(); + held.sort(); + assert_eq!( + (status, account["role"].clone(), held), + ( + StatusCode::OK, + json!(test_case.to), + test_case + .expected_roles + .iter() + .map(|r| (*r).to_owned()) + .collect::>() + ), + "{}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_server_without_sign_in_when_asked_how_people_sign_in_then_it_answers_keys_only() { + let test_cases = [ + LoginModeTestCase { + description: "a server without sign-in for people", + login: no_sign_in, + expected_status: StatusCode::OK, + expected_mode: "keys", + }, + LoginModeTestCase { + description: "a server with password sign-in", + login: password_sign_in, + expected_status: StatusCode::NOT_FOUND, + expected_mode: "", + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(Backend::Sqlite).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let api = start_api_with_authentication( + store, + ApiAuthentication { + login: (test_case.login)(), + ..ApiAuthentication::default() + }, + ) + .await; + let response = script() + .get(format!("{}/api/auth/login-mode", api.url)) + .header(HOST, "control.example.com") + .send() + .await + .expect("login mode"); + let status = response.status(); + let body: Value = response.json().await.unwrap_or(Value::Null); + assert_eq!( + (status, body["login_mode"].as_str().unwrap_or_default()), + (test_case.expected_status, test_case.expected_mode), + "{}", + test_case.description + ); + stop_api(api).await; + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index 460a87cc43..a74c8c82fd 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -120,6 +120,15 @@ pub(crate) struct LocationHealthTestCase { pub(crate) expected_observations: usize, } +pub(crate) struct RepublishTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) publishes: bool, + pub(crate) outcome: fn(uuid::Uuid) -> crate::platform::models::LocationWorkOutcome, + pub(crate) expected_state: crate::platform::models::RepublishState, + pub(crate) expected_error: Option<&'static str>, +} + pub(crate) struct LocationWorkTestCase { pub(crate) description: &'static str, pub(crate) backend: Backend, @@ -352,6 +361,51 @@ pub(crate) struct OlderNodeFinished { skipped_because_of: Option, } +/// The run report shape a server had before run nodes recorded rows, progress and `not_run`. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +#[allow(dead_code)] +pub(crate) struct PreviousRunReport { + event_id: uuid::Uuid, + run_id: uuid::Uuid, + claim_id: Option, + change: PreviousRunChange, +} + +#[derive(serde::Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +#[allow(dead_code)] +pub(crate) enum PreviousRunChange { + NodeStarted { + node_key: String, + }, + NodeFinished { + node_key: String, + outcome: PreviousNodeOutcome, + rows_affected: Option, + error_code: Option, + skipped_because_of: Option, + error_message: Option, + }, +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "snake_case")] +#[allow(dead_code)] +pub(crate) enum PreviousNodeOutcome { + Success, + Warn, + Failed, + Skipped, + Cancelled, +} + +pub(crate) struct PreviousServerTestCase { + pub(crate) description: &'static str, + pub(crate) change: crate::runs::models::RunChange, + pub(crate) expected_upgrade_refusal: bool, +} + pub(crate) struct PlanTestCase { pub(crate) description: &'static str, pub(crate) backend: Backend, @@ -531,3 +585,123 @@ pub(crate) struct NoPasswordPeopleTestCase { pub(crate) login: fn(uuid::Uuid) -> crate::api::models::HumanLogin, pub(crate) expected_status: reqwest::StatusCode, } + +pub(crate) struct ServiceAccountLifecycleTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// `sqbk_` and the random characters after it. + pub(crate) expected_key_length: usize, + /// Keys that work while a rotation's overlap lasts: the new one and the replaced one. + pub(crate) expected_overlap_keys: usize, +} + +pub(crate) struct ServiceAccountPermissionTestCase { + pub(crate) description: &'static str, + /// The built-in role of the person who asks. + pub(crate) role: crate::credentials::models::BuiltinRole, + pub(crate) expected_list: reqwest::StatusCode, + pub(crate) expected_create: reqwest::StatusCode, +} + +pub(crate) struct ImportedKeyTestCase { + pub(crate) description: &'static str, + pub(crate) key: &'static str, + /// Part of the refusal. + pub(crate) expected_error: &'static str, +} + +pub(crate) struct ImportedKeyAcceptedTestCase { + pub(crate) description: &'static str, + pub(crate) key: &'static str, + pub(crate) expected_origin: &'static str, + pub(crate) expected_status: reqwest::StatusCode, +} + +pub(crate) struct PersonImportTestCase { + pub(crate) description: &'static str, + pub(crate) expected_error: &'static str, +} + +/// Adds a request's credentials, or none. +pub(crate) type Authorize = fn(reqwest::RequestBuilder, &str) -> reqwest::RequestBuilder; + +pub(crate) struct ProxyKeyTestCase { + pub(crate) description: &'static str, + /// The proxy's only trusted peer; the test client is `127.0.0.1`. + pub(crate) trusted_peer: &'static str, + pub(crate) authorize: Authorize, + pub(crate) expected_status: reqwest::StatusCode, + /// Whom the request authenticated as; empty when it was refused. + pub(crate) expected_name: &'static str, +} + +pub(crate) struct ProxyBindingTestCase { + pub(crate) description: &'static str, + pub(crate) expected_status: reqwest::StatusCode, +} + +pub(crate) struct KeyOnlyTestCase { + pub(crate) description: &'static str, + pub(crate) authorize: Authorize, + pub(crate) expected_status: reqwest::StatusCode, + pub(crate) expected_cache_control: &'static str, +} + +pub(crate) struct KeyedRoleTestCase { + pub(crate) description: &'static str, + /// The role of the service account whose key makes the change. + pub(crate) role: crate::credentials::models::BuiltinRole, + /// The route, with `{target}`, `{key}`, `{person}` and `{sole_admin}` filled in. + pub(crate) path: &'static str, + pub(crate) body: &'static str, + pub(crate) expected_status: reqwest::StatusCode, + pub(crate) expected_denials: usize, +} + +pub(crate) struct ServiceAccountRoleTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) from: crate::credentials::models::BuiltinRole, + pub(crate) to: &'static str, + pub(crate) expected_roles: &'static [&'static str], +} + +pub(crate) struct LoginModeTestCase { + pub(crate) description: &'static str, + pub(crate) login: fn() -> crate::api::models::HumanLogin, + pub(crate) expected_status: reqwest::StatusCode, + pub(crate) expected_mode: &'static str, +} + +/// One request to a development listener, with `{port}` standing for the listener's port. +pub(crate) struct DevelopmentHostTestCase { + pub(crate) description: &'static str, + pub(crate) bind: &'static str, + pub(crate) allowed: &'static [&'static str], + pub(crate) host: &'static str, + pub(crate) origin: Option<&'static str>, + pub(crate) expected_status: reqwest::StatusCode, +} + +/// A development listener beyond loopback without the opt-in. +pub(crate) struct DevelopmentListenerTestCase { + pub(crate) description: &'static str, + pub(crate) bind: &'static str, + pub(crate) expected_refusal: &'static str, +} + +pub(crate) fn republish_published( + snapshot_id: uuid::Uuid, +) -> crate::platform::models::LocationWorkOutcome { + crate::platform::models::LocationWorkOutcome::Published { + snapshot_id, + generation: 2, + } +} + +pub(crate) fn republish_failed(_: uuid::Uuid) -> crate::platform::models::LocationWorkOutcome { + crate::platform::models::LocationWorkOutcome::PublishFailed { + generation: 2, + error: "orders does not parse".into(), + } +} diff --git a/crates/sqlbuild-orchestration/tests/api/test_worker.rs b/crates/sqlbuild-orchestration/tests/api/test_worker.rs index d43d66c30c..344524d5e8 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_worker.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_worker.rs @@ -25,8 +25,8 @@ use crate::api::tests::helpers::{start_api, stop_api}; use crate::api::tests::output_helpers::{chunk, output_contract}; use crate::api::tests::recall_helpers::recall_contract; use crate::api::tests::test_types::{ - ApiContractTestCase, OlderNodeReport, OlderServerReportTestCase, TestApi, - WorkerDeadlineTestCase, WorkerRedirectTestCase, + ApiContractTestCase, OlderNodeReport, OlderServerReportTestCase, PreviousRunReport, + PreviousServerTestCase, TestApi, WorkerDeadlineTestCase, WorkerRedirectTestCase, }; use crate::credentials::tests::location_helpers::create_location; use crate::runs::tests::helpers::{queue, request, snapshot}; @@ -197,6 +197,8 @@ fn given_a_claimed_run_when_a_worker_connects_then_verification_precedes_start_a node_key: "orders".into(), outcome: NodeOutcome::Success, rows_affected: Some(7), + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, @@ -443,6 +445,8 @@ fn given_an_older_server_when_a_worker_reports_error_text_then_the_refusal_asks_ node_key: "model:orders".into(), outcome: NodeOutcome::Failed, rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: Some("R002".into()), skipped_because_of: None, error_message: test_case.error_message.map(str::to_owned), @@ -561,3 +565,95 @@ fn given_a_slow_recall_server_when_the_delivery_deadline_expires_then_the_native }); } } + +#[test] +fn given_a_server_older_than_node_results_when_a_worker_reports_them_then_the_refusal_asks_for_a_server_upgrade() + { + let finished = |outcome, table_rows| RunChange::NodeFinished { + node_key: "model:orders".into(), + outcome, + rows_affected: None, + table_rows, + no_change_reason: None, + error_code: None, + skipped_because_of: None, + error_message: None, + }; + let test_cases = [ + PreviousServerTestCase { + description: "a report without the new facts keeps working", + change: finished(NodeOutcome::Success, None), + expected_upgrade_refusal: false, + }, + PreviousServerTestCase { + description: "a rebuilt table's row count names the upgrade order", + change: finished(NodeOutcome::Success, Some(500)), + expected_upgrade_refusal: true, + }, + PreviousServerTestCase { + description: "a node the run never reached names the upgrade order", + change: finished(NodeOutcome::NotRun, None), + expected_upgrade_refusal: true, + }, + PreviousServerTestCase { + description: "rows written so far name the upgrade order", + change: RunChange::NodeProgress { + node_key: "model:orders".into(), + rows_so_far: 120, + }, + expected_upgrade_refusal: true, + }, + ]; + run(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("isolated older server"); + let url = format!("http://{}", listener.local_addr().expect("address")); + let application = Router::new().route( + "/api/runs/{run_id}/events", + axum::routing::post(|axum::Json(_): axum::Json| async { + axum::Json(serde_json::json!({"applied": true})) + }), + ); + let (shutdown, signal) = tokio::sync::oneshot::channel(); + let task = tokio::spawn(async move { + axum::serve(listener, application) + .with_graceful_shutdown(async { + let _ = signal.await; + }) + .await + .map_err(ControlError::from) + }); + let api = TestApi { + url, + shutdown, + task, + }; + let client = connect_worker( + &api.url, + "synthetic-worker-bearer", + (Uuid::now_v7(), Uuid::now_v7()), + ) + .expect("worker client"); + for test_case in test_cases { + let reported = client.report(Uuid::now_v7(), test_case.change).await; + let message = reported.as_ref().err().map(ToString::to_string); + assert_eq!( + ( + reported.is_ok(), + matches!(reported, Err(WorkerError::OlderServer)), + message + .is_some_and(|text| text.contains("upgrade the server before its workers")), + ), + ( + !test_case.expected_upgrade_refusal, + test_case.expected_upgrade_refusal, + test_case.expected_upgrade_refusal + ), + "{}", + test_case.description + ); + } + stop_api(api).await; + }); +} diff --git a/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs b/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs index 1189eace22..1d2dc1f7de 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/test_project_roles.rs @@ -16,10 +16,14 @@ use crate::credentials::tests::role_helpers::{ member_listings, member_trigger_change, member_trigger_changes, orders_grant, publish_customers_trigger, publish_support_role, role_changes, role_fixture, }; -use crate::credentials::tests::test_types::{ProjectRoleTestCase, RolesFileTestCase}; +use crate::credentials::tests::test_types::{ + ProjectRoleTestCase, RolesFileTestCase, UnreadableJobToggleTestCase, +}; use crate::declarations::models::TriggerChange; -use crate::runs::tests::helpers::snapshot; +use crate::runs::tests::helpers::{rows, snapshot}; +use crate::scheduler::tests::contracts::helpers::store_old_job_definitions; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::constants::UNREADABLE_PUBLICATION; use crate::store::errors::ControlError; use crate::store::main::migrate_store::migrate_store; use crate::store::main::{begin::begin, commit::commit, query::query}; @@ -27,6 +31,8 @@ use crate::store::models::{Parameter, TransactionMode}; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store::tests::store_test_types::Backend; +const ALL_NODES: &[&str] = &["customers", "inventory", "orders", "products"]; +const TOGGLE_DENIED: &str = "missing trigger.toggle permission for this target"; const ADHOC_DENIED: &str = "missing run.adhoc permission for this target"; #[test] @@ -319,6 +325,130 @@ fn given_grant_outside_a_triggers_job_when_the_member_overrides_it_then_both_tri } } +#[test] +fn given_a_schedule_whose_job_cannot_be_read_when_a_member_toggles_it_then_pause_and_resume_need_the_whole_target() + { + let test_cases = [ + UnreadableJobToggleTestCase { + description: "SQLite pauses and resumes an unreadable job's schedule with the whole target", + backend: Backend::Sqlite, + nodes: ALL_NODES, + earlier_forms: &["project"], + expected_outcomes: [Ok(true), Ok(true), Err(UNREADABLE_PUBLICATION)], + expected_statuses: ["paused", "running", "running"], + }, + UnreadableJobToggleTestCase { + description: "SQLite refuses an unreadable job's schedule with only that job's nodes", + backend: Backend::Sqlite, + nodes: &["customers"], + earlier_forms: &["project"], + expected_outcomes: [ + Err(TOGGLE_DENIED), + Err(TOGGLE_DENIED), + Err(UNREADABLE_PUBLICATION), + ], + expected_statuses: ["running", "running", "running"], + }, + UnreadableJobToggleTestCase { + description: "SQLite still toggles a readable job's schedule with only that job's nodes", + backend: Backend::Sqlite, + nodes: &["customers"], + earlier_forms: &[], + expected_outcomes: [Ok(true), Ok(true), Ok(true)], + expected_statuses: ["paused", "running", "running"], + }, + UnreadableJobToggleTestCase { + description: "SQLite still refuses a readable job's schedule without that job's nodes", + backend: Backend::Sqlite, + nodes: &["orders"], + earlier_forms: &[], + expected_outcomes: [Err(TOGGLE_DENIED), Err(TOGGLE_DENIED), Err(TOGGLE_DENIED)], + expected_statuses: ["running", "running", "running"], + }, + UnreadableJobToggleTestCase { + description: "PostgreSQL pauses and resumes an unreadable job's schedule with the whole target", + backend: Backend::Postgres, + nodes: ALL_NODES, + earlier_forms: &["project"], + expected_outcomes: [Ok(true), Ok(true), Err(UNREADABLE_PUBLICATION)], + expected_statuses: ["paused", "running", "running"], + }, + UnreadableJobToggleTestCase { + description: "PostgreSQL refuses an unreadable job's schedule with only that job's nodes", + backend: Backend::Postgres, + nodes: &["customers"], + earlier_forms: &["project"], + expected_outcomes: [ + Err(TOGGLE_DENIED), + Err(TOGGLE_DENIED), + Err(UNREADABLE_PUBLICATION), + ], + expected_statuses: ["running", "running", "running"], + }, + UnreadableJobToggleTestCase { + description: "PostgreSQL still toggles a readable job's schedule with only that job's nodes", + backend: Backend::Postgres, + nodes: &["customers"], + earlier_forms: &[], + expected_outcomes: [Ok(true), Ok(true), Ok(true)], + expected_statuses: ["paused", "running", "running"], + }, + UnreadableJobToggleTestCase { + description: "PostgreSQL still refuses a readable job's schedule without that job's nodes", + backend: Backend::Postgres, + nodes: &["orders"], + earlier_forms: &[], + expected_outcomes: [Err(TOGGLE_DENIED), Err(TOGGLE_DENIED), Err(TOGGLE_DENIED)], + expected_statuses: ["running", "running", "running"], + }, + ]; + let mut completed = 0; + for test_case in test_cases { + run(async { + let fixture = open_test_store(test_case.backend) + .await + .expect("required backend"); + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let roles = role_fixture(store).await; + let grants = json!([orders_grant( + json!(["view", "trigger.toggle"]), + test_case.nodes + )]); + publish_customers_trigger(store, roles.location_id, (2, grants)).await; + for form in test_case.earlier_forms { + store_old_job_definitions(store, form).await; + } + let mut outcomes: Vec> = Vec::new(); + let mut statuses: Vec = Vec::new(); + for change in [ + TriggerChange::Pause, + TriggerChange::Enable, + TriggerChange::ResetDefault, + ] { + outcomes.push(member_trigger_change(store, &roles, change).await); + let state = rows(store, "SELECT status FROM sqb_trigger_state", vec![]).await; + statuses.push(state[0]["status"].as_str().expect("status").to_owned()); + } + assert_eq!( + (outcomes, statuses), + ( + test_case + .expected_outcomes + .map(|expected| expected.map_err(str::to_owned)) + .to_vec(), + test_case.expected_statuses.map(str::to_owned).to_vec(), + ), + "{}", + test_case.description + ); + completed += 1; + close_test_store(fixture).await; + }); + } + assert_eq!(completed, 8, "both backends run"); +} + #[test] fn given_trigger_overrides_when_a_member_reads_their_history_then_only_full_view_sees_them_newest_first() { diff --git a/crates/sqlbuild-orchestration/tests/credentials/test_types.rs b/crates/sqlbuild-orchestration/tests/credentials/test_types.rs index c309a0a9b5..903751530a 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/test_types.rs @@ -68,3 +68,15 @@ pub(crate) struct RolesFileTestCase { pub(crate) text: &'static str, pub(crate) expected_compiled: Result<(Value, Vec<&'static str>), &'static str>, } + +pub(crate) struct UnreadableJobToggleTestCase { + pub(crate) description: &'static str, + pub(crate) backend: crate::store::tests::store_test_types::Backend, + /// The nodes the member may toggle; the schedule's job writes only `customers`. + pub(crate) nodes: &'static [&'static str], + /// The forms an earlier release left the stored job in; none leaves it readable. + pub(crate) earlier_forms: &'static [&'static str], + /// Pause, resume, then reset to the published default. + pub(crate) expected_outcomes: [Result; 3], + pub(crate) expected_statuses: [&'static str; 3], +} diff --git a/crates/sqlbuild-orchestration/tests/discovered_sets/helpers.rs b/crates/sqlbuild-orchestration/tests/discovered_sets/helpers.rs new file mode 100644 index 0000000000..ee78d1ddc8 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/discovered_sets/helpers.rs @@ -0,0 +1,40 @@ +//! Discovered sets built from item IDs and the items each waits on. + +use std::collections::BTreeMap; + +use chrono::{DateTime, TimeZone, Utc}; + +use crate::discovered_sets::models::{DiscoveredItem, DiscoveredResult, ItemDependency}; + +/// A set of `(id, the item IDs it waits on)`. +pub(crate) fn set(items: &[(&str, &[&str])]) -> DiscoveredResult { + DiscoveredResult { + items: items + .iter() + .map(|(id, parents)| DiscoveredItem { + id: (*id).to_owned(), + depends_on: parents + .iter() + .map(|parent| ItemDependency::Item((*parent).to_owned())) + .collect(), + args: BTreeMap::new(), + }) + .collect(), + tags: BTreeMap::new(), + max_parallel: None, + } +} + +/// 09:00 UTC on `day` November 2026. +pub(crate) fn november(day: u32) -> DateTime { + Utc.with_ymd_and_hms(2026, 11, day, 9, 0, 0) + .single() + .expect("a valid November time") +} + +/// The item IDs of `result`, in order. +pub(crate) fn ids(result: Option<&DiscoveredResult>) -> Vec { + result + .map(|result| result.items.iter().map(|item| item.id.clone()).collect()) + .unwrap_or_default() +} diff --git a/crates/sqlbuild-orchestration/tests/discovered_sets/test_contracts.rs b/crates/sqlbuild-orchestration/tests/discovered_sets/test_contracts.rs new file mode 100644 index 0000000000..3ee74efe14 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/discovered_sets/test_contracts.rs @@ -0,0 +1,6 @@ +#[path = "helpers.rs"] +mod helpers; +#[path = "test_discovered_sets.rs"] +mod test_discovered_sets; +#[path = "test_types.rs"] +mod test_types; diff --git a/crates/sqlbuild-orchestration/tests/discovered_sets/test_discovered_sets.rs b/crates/sqlbuild-orchestration/tests/discovered_sets/test_discovered_sets.rs new file mode 100644 index 0000000000..e8d71cdbf6 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/discovered_sets/test_discovered_sets.rs @@ -0,0 +1,337 @@ +use serde_json::json; + +use crate::discovered_sets::_helpers::digest::discovered_digest; +use crate::discovered_sets::_helpers::problems::discovered_problem; +use crate::discovered_sets::main::discovery_health::discovery_health; +use crate::discovered_sets::main::discovery_summary::discovery_summary; +use crate::discovered_sets::main::item_roots::item_roots; +use crate::discovered_sets::main::parse_check_every::parse_check_every; +use crate::discovered_sets::main::record_attempt::record_attempt; +use crate::discovered_sets::main::result_changed::result_changed; +use crate::discovered_sets::models::DiscoveredSetStatus; +use crate::discovered_sets::tests::helpers::{ids, november, set}; +use crate::discovered_sets::tests::test_types::{ + AttemptTestCase, CheckEveryTestCase, HealthTestCase, ProblemTestCase, RootsTestCase, + SummaryTestCase, +}; +use crate::discovered_sets::types::DiscoveredSets; + +const LONG_ID: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + +#[test] +fn given_a_discover_result_when_checking_it_then_only_a_valid_set_passes() { + let test_cases = [ + ProblemTestCase { + description: "a chain of items with dotted, colon and dash IDs", + result: set(&[("load.orders", &[]), ("fit:orders-1", &["load.orders"])]), + expected_problem: None, + }, + ProblemTestCase { + description: "no items", + result: set(&[]), + expected_problem: Some("the discover function returned no items".to_owned()), + }, + ProblemTestCase { + description: "an ID with a bracket", + result: set(&[("a[1]", &[])]), + expected_problem: Some( + "item ID 'a[1]' uses '['; IDs use only letters, digits and _ . : -".to_owned(), + ), + }, + ProblemTestCase { + description: "an empty ID", + result: set(&[("", &[])]), + expected_problem: Some("an item ID is empty".to_owned()), + }, + ProblemTestCase { + description: "an ID of 201 characters", + result: set(&[(LONG_ID, &[])]), + expected_problem: Some(format!("item ID '{LONG_ID}' is longer than 200 characters")), + }, + ProblemTestCase { + description: "a repeated ID", + result: set(&[("a", &[]), ("a", &[])]), + expected_problem: Some("item ID 'a' appears more than once".to_owned()), + }, + ProblemTestCase { + description: "a dependency on an unknown item", + result: set(&[("a", &["b"])]), + expected_problem: Some( + "item 'a' depends on 'b', which is not an item of the set".to_owned(), + ), + }, + ProblemTestCase { + description: "an item depending on itself", + result: set(&[("a", &["a"])]), + expected_problem: Some("item 'a' depends on itself".to_owned()), + }, + ProblemTestCase { + description: "a cycle", + result: set(&[("a", &["b"]), ("b", &["a"]), ("c", &[])]), + expected_problem: Some("item 'a' is on a dependency cycle".to_owned()), + }, + ]; + + for test_case in test_cases { + assert_eq!( + discovered_problem(&test_case.result), + test_case.expected_problem, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_check_every_text_when_parsing_it_then_units_add_up_from_a_minute() { + let test_cases = [ + CheckEveryTestCase { + description: "minutes", + text: "15m", + expected_seconds: Some(900), + }, + CheckEveryTestCase { + description: "hours and minutes", + text: "1h30m", + expected_seconds: Some(5_400), + }, + CheckEveryTestCase { + description: "a day", + text: "1d", + expected_seconds: Some(86_400), + }, + CheckEveryTestCase { + description: "under a minute", + text: "30s", + expected_seconds: None, + }, + CheckEveryTestCase { + description: "units out of order", + text: "5m1h", + expected_seconds: None, + }, + CheckEveryTestCase { + description: "no unit", + text: "15", + expected_seconds: None, + }, + CheckEveryTestCase { + description: "an unknown unit", + text: "2w", + expected_seconds: None, + }, + ]; + + for test_case in test_cases { + assert_eq!( + parse_check_every(test_case.text).ok(), + test_case.expected_seconds, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_set_that_succeeded_when_an_attempt_follows_then_a_failure_keeps_the_last_good_items() { + let test_cases = [ + AttemptTestCase { + description: "a success without items keeps the last good ones", + attempt: Ok(set(&[])), + expected_ids: vec!["a", "b"], + expected_status: DiscoveredSetStatus::Failed, + expected_error: Some("the discover function returned no items"), + }, + AttemptTestCase { + description: "a success replaces the items", + attempt: Ok(set(&[("c", &[])])), + expected_ids: vec!["c"], + expected_status: DiscoveredSetStatus::Ok, + expected_error: None, + }, + AttemptTestCase { + description: "an error keeps the last good items", + attempt: Err("ssh timeout".to_owned()), + expected_ids: vec!["a", "b"], + expected_status: DiscoveredSetStatus::Failed, + expected_error: Some("ssh timeout"), + }, + AttemptTestCase { + description: "an invalid result fails like an error", + attempt: Ok(set(&[("x", &["y"])])), + expected_ids: vec!["a", "b"], + expected_status: DiscoveredSetStatus::Failed, + expected_error: Some("item 'x' depends on 'y', which is not an item of the set"), + }, + ]; + let previous = record_attempt( + None, + Ok(set(&[("a", &[]), ("b", &["a"])])), + (november(20), None), + ); + + for test_case in test_cases { + let next = record_attempt( + Some(&previous), + test_case.attempt, + (november(21), Some(900)), + ); + + assert_eq!( + ( + ids(next.result.as_ref()), + next.status, + next.error.as_deref() + ), + ( + test_case + .expected_ids + .iter() + .map(|id| (*id).to_owned()) + .collect(), + test_case.expected_status, + test_case.expected_error + ), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_set_when_reading_its_roots_and_digest_then_roots_wait_on_no_item_and_tag_order_does_not_matter() + { + let test_cases = [RootsTestCase { + description: "two roots, and the same tags in another order", + result: set(&[("a", &[]), ("b", &["a"]), ("c", &[])]), + expected_roots: vec!["a", "c"], + expected_same_digest: true, + }]; + + for test_case in test_cases { + let mut first = test_case.result.clone(); + let mut second = test_case.result.clone(); + first.tags = [ + ("release".to_owned(), json!("r1")), + ("plan".to_owned(), json!({"x": 1, "y": 2})), + ] + .into(); + second.tags = [ + ("plan".to_owned(), json!({"y": 2, "x": 1})), + ("release".to_owned(), json!("r1")), + ] + .into(); + let same: bool = discovered_digest(&first).expect("digest") + == discovered_digest(&second).expect("digest"); + + assert_eq!( + (item_roots(&first).into_iter().collect::>(), same), + ( + test_case + .expected_roots + .iter() + .map(|id| (*id).to_owned()) + .collect(), + test_case.expected_same_digest + ), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_an_attempt_after_a_success_when_summarising_then_failures_name_the_error_and_the_last_good_items() + { + let test_cases = [ + SummaryTestCase { + description: "the same items again", + attempt: Ok(set(&[("a", &[]), ("b", &["a"])])), + expected_summary: "orders_plan 2 items", + expected_changed: false, + }, + SummaryTestCase { + description: "a new item", + attempt: Ok(set(&[("a", &[]), ("b", &["a"]), ("c", &[])])), + expected_summary: "orders_plan 3 items", + expected_changed: true, + }, + SummaryTestCase { + description: "a failure keeps the last good items", + attempt: Err("ssh timeout".to_owned()), + expected_summary: "orders_plan \u{2717} ssh timeout (using last good, 2 items)", + expected_changed: false, + }, + ]; + let previous = record_attempt( + None, + Ok(set(&[("a", &[]), ("b", &["a"])])), + (november(20), None), + ); + + for test_case in test_cases { + let next = record_attempt(Some(&previous), test_case.attempt, (november(21), None)); + let changed = result_changed(Some(&previous), &next); + let sets: DiscoveredSets = [("orders_plan".to_owned(), next)].into(); + + assert_eq!( + (discovery_summary(&sets).as_deref(), changed), + (Some(test_case.expected_summary), test_case.expected_changed), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_first_attempt_when_reporting_health_then_a_set_that_never_succeeded_serves_no_items() { + let test_cases = [ + HealthTestCase { + description: "a failure with no last good result", + attempt: Err("no route".to_owned()), + expected_health: (DiscoveredSetStatus::Failed, 0, Some("no route")), + expected_summary: "returns_plan \u{2717} no route (never discovered)", + }, + HealthTestCase { + description: "a failure with NUL, which PostgreSQL refuses, is kept without it", + attempt: Err("no route\0".to_owned()), + expected_health: (DiscoveredSetStatus::Failed, 0, Some("no route")), + expected_summary: "returns_plan \u{2717} no route (never discovered)", + }, + HealthTestCase { + description: "a failure whose NUL could hide a secret is withheld", + attempt: Err("refused pass\0word=orders-2026".to_owned()), + expected_health: (DiscoveredSetStatus::Failed, 0, Some("[REDACTED]")), + expected_summary: "returns_plan \u{2717} [REDACTED] (never discovered)", + }, + HealthTestCase { + description: "a success", + attempt: Ok(set(&[("a", &[])])), + expected_health: (DiscoveredSetStatus::Ok, 1, None), + expected_summary: "returns_plan 1 item", + }, + ]; + + for test_case in test_cases { + let first = record_attempt(None, test_case.attempt, (november(21), Some(900))); + let sets: DiscoveredSets = [("returns_plan".to_owned(), first)].into(); + let health: Vec<_> = discovery_health(&sets) + .into_iter() + .map(|set| (set.status, set.items, set.error)) + .collect(); + + assert_eq!( + (health, discovery_summary(&sets)), + ( + vec![( + test_case.expected_health.0, + test_case.expected_health.1, + test_case.expected_health.2.map(str::to_owned) + )], + Some(test_case.expected_summary.to_owned()) + ), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/discovered_sets/test_types.rs b/crates/sqlbuild-orchestration/tests/discovered_sets/test_types.rs new file mode 100644 index 0000000000..3eb2d86d3f --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/discovered_sets/test_types.rs @@ -0,0 +1,50 @@ +//! Test case types for discovered sets. + +use crate::discovered_sets::models::{DiscoveredResult, DiscoveredSetStatus}; + +/// A discover function's result and the problem it has, if any. +pub(crate) struct ProblemTestCase { + pub(crate) description: &'static str, + pub(crate) result: DiscoveredResult, + pub(crate) expected_problem: Option, +} + +/// A `check_every` text and its seconds, or `None` when it is refused. +pub(crate) struct CheckEveryTestCase { + pub(crate) description: &'static str, + pub(crate) text: &'static str, + pub(crate) expected_seconds: Option, +} + +/// An attempt after an earlier success, and what the set keeps. +pub(crate) struct AttemptTestCase { + pub(crate) description: &'static str, + pub(crate) attempt: Result, + pub(crate) expected_ids: Vec<&'static str>, + pub(crate) expected_status: DiscoveredSetStatus, + pub(crate) expected_error: Option<&'static str>, +} + +/// A set, its roots, and whether reordering its tags keeps its digest. +pub(crate) struct RootsTestCase { + pub(crate) description: &'static str, + pub(crate) result: DiscoveredResult, + pub(crate) expected_roots: Vec<&'static str>, + pub(crate) expected_same_digest: bool, +} + +/// An attempt after an earlier success, the summary `sqb dev` shows, and whether it changed. +pub(crate) struct SummaryTestCase { + pub(crate) description: &'static str, + pub(crate) attempt: Result, + pub(crate) expected_summary: &'static str, + pub(crate) expected_changed: bool, +} + +/// A first attempt and what the location's health reports of it. +pub(crate) struct HealthTestCase { + pub(crate) description: &'static str, + pub(crate) attempt: Result, + pub(crate) expected_health: (DiscoveredSetStatus, u64, Option<&'static str>), + pub(crate) expected_summary: &'static str, +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/helpers.rs b/crates/sqlbuild-orchestration/tests/run_output/helpers.rs new file mode 100644 index 0000000000..8d9110670a --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/helpers.rs @@ -0,0 +1,182 @@ +//! A claimed run, an output store in a temporary folder, a person who may read evidence, and batches. + +use std::collections::BTreeMap; +use std::path::Path; + +use futures_util::StreamExt; +use uuid::Uuid; + +use crate::authorization::main::people::bootstrap_user::bootstrap_user; +use crate::credentials::models::AuditContext; +use crate::credentials::tests::location_helpers::create_location; +use crate::run_output::_helpers::chunks::level_of; +use crate::run_output::main::open_output_store::open_output_store; +use crate::run_output::models::{ + OutputBatch, OutputLine, OutputPageQuery, OutputRow, OutputSegment, OutputSettings, + OutputStore, OutputStream, +}; +use crate::run_output::tests::test_types::PageStart; +use crate::runs::main::execution::claim_next_run::claim_next_run; +use crate::runs::models::RunClaim; +use crate::runs::tests::helpers::{queue, request, snapshot}; +use crate::scheduler::tests::contracts::helpers::acquire_lease; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::ControlStore; + +/// A migrated store's location and a claimed run that selects `orders`. +pub(crate) async fn claimed_run(store: &ControlStore) -> (Uuid, RunClaim) { + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let published = publish_snapshot(store, &snapshot(location)) + .await + .expect("publish"); + queue( + store, + &request((location, published.snapshot_id), 61, 0, &["orders"]), + ) + .await; + let lease = acquire_lease(store, Uuid::now_v7()) + .await + .expect("elect") + .expect("leader"); + let claim = claim_next_run(store, &lease, &BTreeMap::new(), None) + .await + .expect("claim") + .expect("claimable"); + (location, claim) +} + +/// An output store in `folder`, keeping at most `max_bytes_per_run` of a run. +pub(crate) fn output_store( + store: &ControlStore, + folder: &Path, + max_bytes_per_run: Option, +) -> OutputStore { + open_output_store( + &OutputSettings { + store: Some(format!("file://{}", folder.display())), + max_bytes_per_run, + }, + store, + ) + .expect("output store") +} + +/// An administrator who may read every run's evidence, and the audit context they read with. +pub(crate) async fn reader(store: &ControlStore) -> (AuditContext, Uuid) { + let context = AuditContext { + actor: "test-operator".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let admin = bootstrap_user(store, &context, "orders-admin") + .await + .expect("administrator"); + (context, admin) +} + +pub(crate) fn segment(node_key: Option<&str>, stream: OutputStream, text: &str) -> OutputSegment { + OutputSegment { + node_key: node_key.map(str::to_owned), + stream, + text: text.into(), + dropped_bytes: 0, + } +} + +pub(crate) fn batch(number: u64, segments: Vec) -> OutputBatch { + OutputBatch { + batch: number, + segments, + } +} + +/// How many objects the output store holds. +pub(crate) async fn object_count(output: &OutputStore) -> usize { + output.objects.list(None).count().await +} + +/// A stored line as a page returns it, its level read the way the server reads it. +pub(crate) fn line(number: i64, node_key: &str, stream: OutputStream, text: &str) -> OutputLine { + OutputLine { + number, + node_key: node_key.into(), + stream, + text: text.into(), + at: chrono::DateTime::UNIX_EPOCH, + level: level_of(text), + omitted_before: 0, + } +} + +/// `rows` as JSON with every line's arrival time left out, to compare with lines whose time a test cannot know. +pub(crate) fn timeless(rows: &[OutputRow]) -> serde_json::Value { + let mut value: serde_json::Value = serde_json::to_value(rows).expect("rows"); + for row in value.as_array_mut().expect("rows") { + row["line"]["at"] = serde_json::Value::Null; + row["sample"]["at"] = serde_json::Value::Null; + } + value +} + +/// A page row of one line. +pub(crate) fn line_row(number: i64, node_key: &str, stream: OutputStream, text: &str) -> OutputRow { + OutputRow::Line { + line: line(number, node_key, stream, text), + } +} + +/// A page row folding `count` similar lines from `sample`'s. +pub(crate) fn similar_row(count: i64, sample: OutputLine) -> OutputRow { + OutputRow::Similar { + from: sample.number, + count, + sample, + } +} + +/// A page query for one node's view, or the run's, from `start`. +pub(crate) fn page_query( + (node, stream): (Option<&str>, Option), + start: PageStart, + (limit, collapse, around): (u32, bool, Option), +) -> OutputPageQuery { + OutputPageQuery { + node: node.map(str::to_owned), + stream, + from: start.from, + before: start.before, + tail: start.tail, + limit: Some(limit), + collapse, + around, + } +} + +/// Make the folder holding the run's chunks read-only, or writable again, so deleting them fails or works. +#[cfg(unix)] +pub(crate) async fn set_chunks_writable(output: &OutputStore, folder: &Path, writable: bool) { + use std::os::unix::fs::PermissionsExt; + let first = output + .objects + .list(None) + .next() + .await + .expect("a stored chunk") + .expect("listed"); + let chunks = folder.join(first.location.as_ref()).with_file_name(""); + let mode: u32 = [0o555, 0o755][usize::from(writable)]; + std::fs::set_permissions(&chunks, std::fs::Permissions::from_mode(mode)).expect("permissions"); +} + +/// A case's path, with a leading `/` read as this platform's root, the temporary folder's, so it is absolute there too. +pub(crate) fn platform_path(path: &str) -> std::path::PathBuf { + let temporary: std::path::PathBuf = std::env::temp_dir(); + let root: &std::path::Path = temporary.ancestors().last().expect("a filesystem root"); + path.strip_prefix('/') + .map_or_else(|| std::path::PathBuf::from(path), |rest| root.join(rest)) +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_audit.rs b/crates/sqlbuild-orchestration/tests/run_output/test_audit.rs new file mode 100644 index 0000000000..5823be4f49 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_audit.rs @@ -0,0 +1,119 @@ +//! A page following a run audits its repeated output reads once per window; a search or download is audited each time. + +use crate::credentials::models::DefaultRole; +use crate::run_output::main::publish_output_batch::publish_output_batch; +use crate::run_output::main::read_person_output_index::read_person_output_index; +use crate::run_output::main::read_person_output_page::read_person_output_page; +use crate::run_output::main::search_person_output::search_person_output; +use crate::run_output::models::{OutputSearchQuery, OutputStream}; +use crate::run_output::tests::helpers::{ + batch, claimed_run, output_store, page_query, reader, segment, +}; +use crate::run_output::tests::test_types::{OutputAuditTestCase, PageStart}; +use crate::runs::tests::helpers::rows; +use crate::store::models::Parameter; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_page_following_a_run_when_it_reads_the_output_twice_then_only_searches_are_audited_twice() + { + let test_cases = [ + OutputAuditTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_audits: vec![ + ("output.index", 1), + ("output.page", 1), + ("output.search", 2), + ], + }, + OutputAuditTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_audits: vec![ + ("output.index", 1), + ("output.page", 1), + ("output.search", 2), + ], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (location, claim) = claimed_run(store).await; + let run_id = claim.request.run_id; + publish_output_batch( + store, + &output, + (run_id, claim.claim_id), + batch( + 0, + vec![segment( + Some("model:orders"), + OutputStream::Stdout, + "loaded\n", + )], + ), + ) + .await + .expect("batch"); + let (context, admin) = reader(store).await; + let person = ( + (&context, admin), + (location, "development", run_id), + DefaultRole::None, + ); + let tail = page_query( + (None, None), + PageStart { + tail: true, + ..PageStart::default() + }, + (10, false, None), + ); + let search = OutputSearchQuery { + node: "model:orders".into(), + stream: None, + text: "loaded".into(), + from: None, + direction: None, + }; + for _ in 0..2 { + read_person_output_index(store, person, None) + .await + .expect("index") + .expect("run"); + read_person_output_page(store, &output, person, &tail) + .await + .expect("page") + .expect("run"); + search_person_output(store, &output, person, &search) + .await + .expect("search") + .expect("run"); + } + let mut audits: Vec<(&str, usize)> = Vec::new(); + for (action, _) in &test_case.expected_audits { + let found = rows( + store, + "SELECT event_id FROM sqb_security_audit WHERE action=$1", + vec![Parameter::Text((*action).into())], + ) + .await; + audits.push((action, found.len())); + } + assert_eq!( + audits, test_case.expected_audits, + "{}: audit rows by action", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_cap.rs b/crates/sqlbuild-orchestration/tests/run_output/test_cap.rs new file mode 100644 index 0000000000..002fbd733f --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_cap.rs @@ -0,0 +1,132 @@ +//! Past `max_bytes_per_run` a run keeps its first part and its newest part, and counts the lines left out between them. + +use crate::credentials::models::DefaultRole; +use crate::run_output::main::publish_output_batch::publish_output_batch; +use crate::run_output::main::read_person_output_index::read_person_output_index; +use crate::run_output::main::read_person_output_page::read_person_output_page; +use crate::run_output::models::OutputStream; +use crate::run_output::tests::helpers::{ + batch, claimed_run, object_count, output_store, page_query, reader, segment, +}; +use crate::run_output::tests::test_types::{OutputCapTestCase, PageStart}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_run_past_its_byte_cap_when_its_output_is_read_then_the_first_and_last_parts_remain_with_a_gap() + { + let test_cases = [ + OutputCapTestCase { + description: "SQLite keeps two first and two last batches of six", + backend: Backend::Sqlite, + max_bytes_per_run: 60, + batches: 6, + expected_lines: vec![(1, 0), (2, 0), (5, 2), (6, 0)], + expected_omitted: (30, 2), + expected_objects: 4, + expected_mark_lines: vec![6], + }, + OutputCapTestCase { + description: "PostgreSQL keeps two first and two last batches of six", + backend: Backend::Postgres, + max_bytes_per_run: 60, + batches: 6, + expected_lines: vec![(1, 0), (2, 0), (5, 2), (6, 0)], + expected_omitted: (30, 2), + expected_objects: 4, + expected_mark_lines: vec![6], + }, + OutputCapTestCase { + description: "a run under its cap keeps everything", + backend: Backend::Sqlite, + max_bytes_per_run: 1_000, + batches: 3, + expected_lines: vec![(1, 0), (2, 0), (3, 0)], + expected_omitted: (0, 0), + expected_objects: 3, + expected_mark_lines: vec![3], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), Some(test_case.max_bytes_per_run)); + let (location, claim) = claimed_run(store).await; + for number in 0..test_case.batches { + let word: &str = ["ok ", "error"][usize::from([2, 3, 5].contains(&number))]; + let text = format!("batch {number:02} {word}\n"); + publish_output_batch( + store, + &output, + (claim.request.run_id, claim.claim_id), + batch( + number as u64, + vec![segment(Some("model:orders"), OutputStream::Stdout, &text)], + ), + ) + .await + .expect("batch"); + } + let (context, admin) = reader(store).await; + let person = ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ); + let page = read_person_output_page( + store, + &output, + person, + &page_query( + (Some("model:orders"), None), + PageStart { + from: Some(1), + ..PageStart::default() + }, + (100, false, None), + ), + ) + .await + .expect("page") + .expect("run"); + let rows: serde_json::Value = serde_json::to_value(&page.rows).expect("rows"); + let lines: Vec<(i64, i64)> = rows + .as_array() + .expect("rows") + .iter() + .map(|row| { + ( + row["line"]["number"].as_i64().unwrap_or_default(), + row["line"]["omitted_before"].as_i64().unwrap_or_default(), + ) + }) + .collect(); + assert_eq!(lines, test_case.expected_lines, "{}", test_case.description); + let index = read_person_output_index(store, person, Some("model:orders")) + .await + .expect("index") + .expect("run"); + let mark_lines: Vec = index.marks.iter().map(|mark| mark.line).collect(); + assert_eq!( + ((index.omitted_bytes, index.omitted_lines), mark_lines), + ( + test_case.expected_omitted, + test_case.expected_mark_lines.clone() + ), + "{}", + test_case.description + ); + assert_eq!( + object_count(&output).await, + test_case.expected_objects, + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_contracts.rs b/crates/sqlbuild-orchestration/tests/run_output/test_contracts.rs new file mode 100644 index 0000000000..4d0f267607 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_contracts.rs @@ -0,0 +1,22 @@ +//! Run output: worker batches into zstd chunks, the index, pages, search, download, the size cap and retention. + +#[path = "helpers.rs"] +pub(crate) mod helpers; +#[path = "test_audit.rs"] +mod test_audit; +#[path = "test_cap.rs"] +mod test_cap; +#[path = "test_large.rs"] +mod test_large; +#[path = "test_location.rs"] +mod test_location; +#[path = "test_logs.rs"] +mod test_logs; +#[path = "test_reads.rs"] +mod test_reads; +#[path = "test_retention.rs"] +mod test_retention; +#[path = "test_types.rs"] +pub(crate) mod test_types; +#[path = "test_upload.rs"] +mod test_upload; diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_large.rs b/crates/sqlbuild-orchestration/tests/run_output/test_large.rs new file mode 100644 index 0000000000..b29e17f7bb --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_large.rs @@ -0,0 +1,104 @@ +//! A node printing about 1 GB leaves the control store holding only its small index. + +use std::time::Instant; + +use crate::credentials::models::DefaultRole; +use crate::run_output::constants::BATCH_TEXT_BYTES; +use crate::run_output::main::publish_output_batch::publish_output_batch; +use crate::run_output::main::read_person_output_page::read_person_output_page; +use crate::run_output::models::OutputStream; +use crate::run_output::tests::helpers::{ + batch, claimed_run, output_store, page_query, reader, segment, +}; +use crate::run_output::tests::test_types::{OutputLargeTestCase, PageStart}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_node_printing_a_gigabyte_when_it_is_stored_then_the_control_store_holds_only_the_index() +{ + let test_cases = [OutputLargeTestCase { + description: "about 1 GB of stdout from one node on SQLite", + backend: Backend::Sqlite, + printed_bytes: 1 << 30, + expected_control_bytes_below: 16 * 1024 * 1024, + expected_tail_lines: 2, + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (location, claim) = claimed_run(store).await; + let line = "2026-11-21T10:00:00Z model orders processed partition 000123 rows=48210 status=ok\n"; + let text: String = line.repeat(BATCH_TEXT_BYTES / line.len()); + let batches: usize = test_case.printed_bytes.div_ceil(text.len()); + let started = Instant::now(); + for number in 0..batches { + publish_output_batch( + store, + &output, + (claim.request.run_id, claim.claim_id), + batch( + number as u64, + vec![segment(Some("model:orders"), OutputStream::Stdout, &text)], + ), + ) + .await + .expect("batch"); + } + let directory = fixture.directory.as_ref().expect("SQLite folder"); + let control_bytes: u64 = std::fs::read_dir(directory.path()) + .expect("control folder") + .flatten() + .map(|entry| { + entry + .metadata() + .map(|metadata| metadata.len()) + .unwrap_or_default() + }) + .sum(); + assert!( + control_bytes < test_case.expected_control_bytes_below, + "{}: the control store holds {control_bytes} bytes after {batches} batches in {:?}", + test_case.description, + started.elapsed() + ); + let lines_per_batch = (text.len() / line.len()) as i64; + let (context, admin) = reader(store).await; + let page = read_person_output_page( + store, + &output, + ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ), + &page_query( + (Some("model:orders"), Some(OutputStream::Stdout)), + PageStart { + tail: true, + ..PageStart::default() + }, + (2, false, None), + ), + ) + .await + .expect("tail") + .expect("run"); + assert_eq!( + (page.line_count, page.rows.len()), + ( + lines_per_batch * batches as i64, + test_case.expected_tail_lines + ), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_location.rs b/crates/sqlbuild-orchestration/tests/run_output/test_location.rs new file mode 100644 index 0000000000..4bf6adbe7d --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_location.rs @@ -0,0 +1,140 @@ +//! With no setting output goes beside a SQLite store, or to the user's state folder with PostgreSQL whatever the working directory. + +use crate::run_output::_helpers::folders::default_folder; +use crate::run_output::main::open_output_store::open_output_store; +use crate::run_output::models::OutputSettings; +use crate::run_output::tests::helpers::platform_path; +use crate::run_output::tests::test_types::{OutputDefaultTestCase, OutputLocationTestCase}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_users_folders_when_no_store_is_set_then_the_default_never_depends_on_the_working_directory() + { + let test_cases = [ + OutputDefaultTestCase { + description: "SQLite keeps it beside the control database", + backend: Backend::Sqlite, + state_home: Some("/srv/state"), + home: Some("/home/sqlbuild"), + expected_folder: Some("output"), + }, + OutputDefaultTestCase { + description: "SQLite needs no home", + backend: Backend::Sqlite, + state_home: None, + home: None, + expected_folder: Some("output"), + }, + OutputDefaultTestCase { + description: "PostgreSQL uses XDG_STATE_HOME", + backend: Backend::Postgres, + state_home: Some("/srv/state"), + home: Some("/home/sqlbuild"), + expected_folder: Some("/srv/state/sqlbuild/output"), + }, + OutputDefaultTestCase { + description: "PostgreSQL needs no home beside XDG_STATE_HOME", + backend: Backend::Postgres, + state_home: Some("/srv/state"), + home: None, + expected_folder: Some("/srv/state/sqlbuild/output"), + }, + OutputDefaultTestCase { + description: "PostgreSQL falls back to the state folder in the home", + backend: Backend::Postgres, + state_home: None, + home: Some("/home/sqlbuild"), + expected_folder: Some("/home/sqlbuild/.local/state/sqlbuild/output"), + }, + OutputDefaultTestCase { + description: "an empty XDG_STATE_HOME is ignored", + backend: Backend::Postgres, + state_home: Some(""), + home: Some("/home/sqlbuild"), + expected_folder: Some("/home/sqlbuild/.local/state/sqlbuild/output"), + }, + OutputDefaultTestCase { + description: "a relative XDG_STATE_HOME is ignored", + backend: Backend::Postgres, + state_home: Some("state"), + home: Some("/home/sqlbuild"), + expected_folder: Some("/home/sqlbuild/.local/state/sqlbuild/output"), + }, + OutputDefaultTestCase { + description: "PostgreSQL has no default without a home", + backend: Backend::Postgres, + state_home: None, + home: None, + expected_folder: None, + }, + OutputDefaultTestCase { + description: "a relative home never means the working directory", + backend: Backend::Postgres, + state_home: None, + home: Some("sqlbuild"), + expected_folder: None, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let beside = fixture + .directory + .as_ref() + .map(|directory| directory.path().canonicalize().expect("store folder")) + .unwrap_or_default(); + let folders = ( + test_case.state_home.map(platform_path), + test_case.home.map(platform_path), + ); + assert_eq!( + default_folder(&fixture.store, folders).ok(), + test_case + .expected_folder + .map(|folder| beside.join(platform_path(folder))), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_no_output_setting_when_the_store_opens_then_sqlite_reports_an_absolute_folder_beside_it() { + let test_cases = [OutputLocationTestCase { + description: "SQLite keeps it beside the control database", + backend: Backend::Sqlite, + expected_folder: "output", + }]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let opened = open_output_store(&OutputSettings::default(), &fixture.store) + .expect("the default output store"); + let folder = std::path::Path::new( + opened + .location() + .strip_prefix("file://") + .expect("a local store"), + ); + assert_eq!( + ( + folder.is_absolute(), + folder.is_dir(), + folder.ends_with(test_case.expected_folder) + ), + (true, true, true), + "{}: {}", + test_case.description, + opened.location() + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_logs.rs b/crates/sqlbuild-orchestration/tests/run_output/test_logs.rs new file mode 100644 index 0000000000..dad15e2f05 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_logs.rs @@ -0,0 +1,105 @@ +//! Lines a node logs with `ctx.log` are kept with the run and read back with its output index. + +use uuid::Uuid; + +use crate::credentials::models::DefaultRole; +use crate::run_output::main::read_person_output_index::read_person_output_index; +use crate::run_output::tests::helpers::{claimed_run, reader}; +use crate::run_output::tests::test_types::NodeLogTestCase; +use crate::runs::main::execution::change_run::change_run; +use crate::runs::models::{NodeLogLevel, RunAuthority, RunChange, RunChangeRequest}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_worker_reporting_ctx_log_lines_when_the_output_index_is_read_then_they_read_back_with_their_levels() + { + let test_cases = [ + NodeLogTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_logs: vec![ + ("model:orders", "info", "loaded 3 orders"), + ("model:orders", "warning", "2 orders had no customer"), + ], + }, + NodeLogTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_logs: vec![ + ("model:orders", "info", "loaded 3 orders"), + ("model:orders", "warning", "2 orders had no customer"), + ], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let (location, claim) = claimed_run(store).await; + let worker = RunAuthority::Worker { + run_id: claim.request.run_id, + claim_id: claim.claim_id, + }; + let report = |change| RunChangeRequest { + event_id: Uuid::now_v7(), + run_id: claim.request.run_id, + claim_id: Some(claim.claim_id), + change, + }; + let log = |level, message: &str| RunChange::NodeLog { + node_key: "model:orders".into(), + level, + message: message.into(), + }; + for change in [ + RunChange::Started, + log(NodeLogLevel::Info, "loaded 3 orders"), + log(NodeLogLevel::Warning, "2 orders had no customer"), + ] { + change_run(store, worker, &report(change)) + .await + .expect("worker fact"); + } + let oversized = change_run( + store, + worker, + &report(log(NodeLogLevel::Error, &"x".repeat(5000))), + ) + .await; + assert!( + oversized.is_err(), + "{}: an oversized message is refused", + test_case.description + ); + let (context, admin) = reader(store).await; + let index = read_person_output_index( + store, + ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ), + None, + ) + .await + .expect("index") + .expect("run"); + let logs: Vec<(&str, &str, &str)> = index + .logs + .iter() + .map(|line| { + ( + line.node_key.as_str(), + line.level.as_str(), + line.message.as_str(), + ) + }) + .collect(); + assert_eq!(logs, test_case.expected_logs, "{}", test_case.description); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_reads.rs b/crates/sqlbuild-orchestration/tests/run_output/test_reads.rs new file mode 100644 index 0000000000..98e8d55ae4 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_reads.rs @@ -0,0 +1,664 @@ +//! A person reads a node's output numbered across its two streams, or the run's numbered in the order printed: pages either way, one stream, folded similar lines, two-way search and download. + +use futures_util::StreamExt; +use uuid::Uuid; + +use crate::credentials::models::DefaultRole; +use crate::run_output::main::download_person_output::download_person_output; +use crate::run_output::main::publish_output_batch::publish_output_batch; +use crate::run_output::main::read_person_output_index::read_person_output_index; +use crate::run_output::main::read_person_output_page::read_person_output_page; +use crate::run_output::main::search_person_output::search_person_output; +use crate::run_output::models::{ + OutputDownloadQuery, OutputLevel, OutputMark, OutputRow, OutputSearch, OutputSearchQuery, + OutputStream, SearchDirection, +}; +use crate::run_output::tests::helpers::{ + batch, claimed_run, line, line_row, output_store, page_query, reader, segment, similar_row, + timeless, +}; +use crate::run_output::tests::test_types::{ + OutputFoldTestCase, OutputNulTestCase, OutputReadTestCase, OutputSearchTestCase, PageRead, + PageStart, SearchRead, +}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +const ORDERS: &str = "model:orders"; +const CUSTOMERS: &str = "model:customers"; + +#[test] +fn given_worker_batches_when_a_person_reads_a_node_or_the_run_then_pages_streams_marks_and_downloads_agree() + { + let (out, err) = (OutputStream::Stdout, OutputStream::Stderr); + let marks = || { + vec![ + OutputMark { + line: 4, + stream: err, + level: OutputLevel::Error, + text: "Traceback (most recent call last):".into(), + }, + OutputMark { + line: 5, + stream: err, + level: OutputLevel::Error, + text: "ValueError: bad amount".into(), + }, + OutputMark { + line: 7, + stream: out, + level: OutputLevel::Warning, + text: "warning: slow load".into(), + }, + ] + }; + let pages = || { + vec![ + PageRead { + node: Some(ORDERS), + stream: None, + start: PageStart { + from: Some(2), + ..PageStart::default() + }, + limit: 3, + expected_rows: vec![ + line_row(2, ORDERS, out, "line 2"), + line_row(3, ORDERS, out, "line 3"), + line_row(4, ORDERS, err, "Traceback (most recent call last):"), + ], + expected_links: (Some(5), Some(2)), + }, + PageRead { + node: Some(ORDERS), + stream: Some(out), + start: PageStart { + from: Some(1), + ..PageStart::default() + }, + limit: 10, + expected_rows: vec![ + line_row(1, ORDERS, out, "line 1"), + line_row(2, ORDERS, out, "line 2"), + line_row(3, ORDERS, out, "line 3"), + line_row(6, ORDERS, out, "line 4"), + line_row(7, ORDERS, out, "warning: slow load"), + line_row(8, ORDERS, out, "line 6"), + ], + expected_links: (None, None), + }, + PageRead { + node: Some(ORDERS), + stream: None, + start: PageStart { + tail: true, + ..PageStart::default() + }, + limit: 2, + expected_rows: vec![ + line_row(7, ORDERS, out, "warning: slow load"), + line_row(8, ORDERS, out, "line 6"), + ], + expected_links: (None, Some(7)), + }, + PageRead { + node: Some(ORDERS), + stream: None, + start: PageStart { + before: Some(4), + ..PageStart::default() + }, + limit: 2, + expected_rows: vec![ + line_row(2, ORDERS, out, "line 2"), + line_row(3, ORDERS, out, "line 3"), + ], + expected_links: (Some(4), Some(2)), + }, + PageRead { + node: None, + stream: None, + start: PageStart { + tail: true, + ..PageStart::default() + }, + limit: 3, + expected_rows: vec![ + line_row(8, ORDERS, out, "warning: slow load"), + line_row(9, ORDERS, out, "line 6"), + line_row(10, CUSTOMERS, out, "loaded customers"), + ], + expected_links: (None, Some(8)), + }, + PageRead { + node: None, + stream: Some(err), + start: PageStart { + from: Some(1), + ..PageStart::default() + }, + limit: 5, + expected_rows: vec![ + line_row(5, ORDERS, err, "Traceback (most recent call last):"), + line_row(6, ORDERS, err, "ValueError: bad amount"), + ], + expected_links: (None, None), + }, + ] + }; + let downloads = ( + "line 1\nline 2\nline 3\nTraceback (most recent call last):\nValueError: bad amount\nline 4\nwarning: slow load\nline 6\n", + "Traceback (most recent call last):\nValueError: bad amount\n", + ); + let test_cases = [ + OutputReadTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_nodes: vec![(CUSTOMERS, 1, 1, 0), (ORDERS, 8, 6, 2), ("run", 1, 1, 0)], + expected_run_lines: 10, + expected_marks: marks(), + pages: pages(), + expected_downloads: downloads, + }, + OutputReadTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_nodes: vec![(CUSTOMERS, 1, 1, 0), (ORDERS, 8, 6, 2), ("run", 1, 1, 0)], + expected_run_lines: 10, + expected_marks: marks(), + pages: pages(), + expected_downloads: downloads, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (location, claim) = claimed_run(store).await; + let worker = (claim.request.run_id, claim.claim_id); + let batches = [ + batch( + 0, + vec![ + segment(None, out, "starting\n"), + segment(Some(ORDERS), out, "line 1\nline 2\nline 3\n"), + segment( + Some(ORDERS), + err, + "Traceback (most recent call last):\nValueError: bad amount\n", + ), + ], + ), + batch( + 1, + vec![ + segment(Some(ORDERS), out, "line 4\nwarning: slow load\nline 6\n"), + segment(Some(CUSTOMERS), out, "loaded customers\n"), + ], + ), + ]; + for sent in batches.iter().chain(&batches[1..]) { + publish_output_batch(store, &output, worker, sent.clone()) + .await + .expect("batch"); + } + let refused = publish_output_batch( + store, + &output, + (claim.request.run_id, Uuid::now_v7()), + batches[1].clone(), + ) + .await; + assert!( + refused.is_err(), + "{}: another claim cannot publish", + test_case.description + ); + let (context, admin) = reader(store).await; + let person = ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ); + let index = read_person_output_index(store, person, Some(ORDERS)) + .await + .expect("index") + .expect("run"); + let nodes: Vec<(&str, i64, i64, i64)> = index + .nodes + .iter() + .map(|node| { + ( + node.node_key.as_str(), + node.line_count, + node.stdout_lines, + node.stderr_lines, + ) + }) + .collect(); + assert_eq!( + (nodes, index.line_count, &index.marks), + ( + test_case.expected_nodes.clone(), + test_case.expected_run_lines, + &test_case.expected_marks + ), + "{}: a retried batch is stored once", + test_case.description + ); + for read in &test_case.pages { + let page = read_person_output_page( + store, + &output, + person, + &page_query( + (read.node, read.stream), + read.start, + (read.limit, false, None), + ), + ) + .await + .expect("page") + .expect("run"); + assert_eq!( + (timeless(&page.rows), (page.next, page.previous)), + (timeless(&read.expected_rows), read.expected_links), + "{}: {:?} {:?} from {:?}", + test_case.description, + read.node, + read.stream, + (read.start.from, read.start.before, read.start.tail) + ); + } + let mut downloads: Vec = Vec::new(); + for stream in [None, Some(err)] { + let parts: Vec = download_person_output( + store, + &output, + person, + &OutputDownloadQuery { + node: ORDERS.into(), + stream, + }, + ) + .await + .expect("download") + .expect("run") + .map(|part| part.expect("chunk")) + .collect() + .await; + downloads.push(parts.concat()); + } + assert_eq!( + (downloads[0].as_str(), downloads[1].as_str()), + test_case.expected_downloads, + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_marked_line_with_a_nul_when_published_then_its_batch_and_the_lines_after_it_read_back() { + let out = OutputStream::Stdout; + let printed = [ + "loading\nerror: bad\0amount\nloaded the rest\n", + "next batch\n", + ]; + let expected_mark = "error: badamount"; + let expected_lines = [ + "loading", + "error: bad\0amount", + "loaded the rest", + "next batch", + ]; + let test_cases = [ + OutputNulTestCase { + description: "SQLite", + backend: Backend::Sqlite, + printed, + expected_mark, + expected_lines, + }, + OutputNulTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + printed, + expected_mark, + expected_lines, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (location, claim) = claimed_run(store).await; + let worker = (claim.request.run_id, claim.claim_id); + for (number, text) in (0_u64..).zip(test_case.printed) { + let sent = batch(number, vec![segment(Some(ORDERS), out, text)]); + publish_output_batch(store, &output, worker, sent) + .await + .expect("batch"); + } + let (context, admin) = reader(store).await; + let person = ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ); + let index = read_person_output_index(store, person, Some(ORDERS)) + .await + .expect("index") + .expect("run"); + let start = PageStart { + from: Some(1), + ..PageStart::default() + }; + let query = page_query((Some(ORDERS), None), start, (10, false, None)); + let page = read_person_output_page(store, &output, person, &query) + .await + .expect("page") + .expect("run"); + let marks: Vec<&str> = index.marks.iter().map(|mark| mark.text.as_str()).collect(); + let expected_rows: Vec = (1_i64..) + .zip(test_case.expected_lines) + .map(|(number, text)| line_row(number, ORDERS, out, text)) + .collect(); + assert_eq!( + (marks, timeless(&page.rows)), + (vec![test_case.expected_mark], timeless(&expected_rows)), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_runs_of_similar_lines_when_a_folding_page_is_read_then_four_or_more_fold_except_around_a_jump() + { + let out = OutputStream::Stdout; + let printed: &str = "row 1 ok\nrow 2 ok\nrow 3 ok\nrow 4 ok\nrow 5 ok\nrow 6 ok\nrow 7 ok\nrow 8 ok\nrow 9 ok\nrow 10 ok\ndone\nx 1\nx 2\n"; + let row = |number: i64| line_row(number, ORDERS, out, &format!("row {number} ok")); + let test_cases = [ + OutputFoldTestCase { + description: "ten similar lines fold, two do not", + backend: Backend::Sqlite, + printed, + start: PageStart { + from: Some(1), + ..PageStart::default() + }, + limit: 10, + around: None, + expected_rows: vec![ + similar_row(10, line(1, ORDERS, out, "row 1 ok")), + line_row(11, ORDERS, out, "done"), + line_row(12, ORDERS, out, "x 1"), + line_row(13, ORDERS, out, "x 2"), + ], + expected_span: (1, 14), + }, + OutputFoldTestCase { + description: "lines near a jump stay open and the four before them fold", + backend: Backend::Postgres, + printed, + start: PageStart { + from: Some(1), + ..PageStart::default() + }, + limit: 20, + around: Some(8), + expected_rows: vec![ + similar_row(4, line(1, ORDERS, out, "row 1 ok")), + row(5), + row(6), + row(7), + row(8), + row(9), + row(10), + line_row(11, ORDERS, out, "done"), + line_row(12, ORDERS, out, "x 1"), + line_row(13, ORDERS, out, "x 2"), + ], + expected_span: (1, 14), + }, + OutputFoldTestCase { + description: "a one-row page reads its folded run to the end", + backend: Backend::Sqlite, + printed, + start: PageStart { + from: Some(1), + ..PageStart::default() + }, + limit: 1, + around: None, + expected_rows: vec![similar_row(10, line(1, ORDERS, out, "row 1 ok"))], + expected_span: (1, 11), + }, + OutputFoldTestCase { + description: "a backward page folds the run before it", + backend: Backend::Postgres, + printed, + start: PageStart { + before: Some(11), + ..PageStart::default() + }, + limit: 1, + around: None, + expected_rows: vec![similar_row(10, line(1, ORDERS, out, "row 1 ok"))], + expected_span: (1, 11), + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (location, claim) = claimed_run(store).await; + publish_output_batch( + store, + &output, + (claim.request.run_id, claim.claim_id), + batch(0, vec![segment(Some(ORDERS), out, test_case.printed)]), + ) + .await + .expect("batch"); + let (context, admin) = reader(store).await; + let page = read_person_output_page( + store, + &output, + ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ), + &page_query( + (Some(ORDERS), None), + test_case.start, + (test_case.limit, true, test_case.around), + ), + ) + .await + .expect("page") + .expect("run"); + assert_eq!( + (timeless(&page.rows), (page.from, page.to)), + (timeless(&test_case.expected_rows), test_case.expected_span), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_node_output_when_searched_either_way_then_small_output_counts_and_wraps_and_large_output_continues() + { + let (out, err) = (OutputStream::Stdout, OutputStream::Stderr); + let found = |line: i64, count: i64, rank: i64| OutputSearch { + line: Some(line), + count: Some(count), + rank: Some(rank), + continue_from: None, + }; + let partial = |line: Option, continue_from: Option| OutputSearch { + line, + count: None, + rank: None, + continue_from, + }; + let search = |text: &'static str, from: i64, direction: SearchDirection| SearchRead { + text, + from, + direction, + }; + let (forward, backward) = (SearchDirection::Forward, SearchDirection::Backward); + let test_cases = [ + OutputSearchTestCase { + description: "SQLite output small enough to scan whole", + backend: Backend::Sqlite, + filler_batches: 0, + searches: vec![ + search("line", 1, forward), + search("line", 4, forward), + search("line", 5, backward), + search("line", 9, forward), + search("VALUEERROR", 1, forward), + search("zzz", 1, forward), + ], + expected_results: vec![ + found(1, 5, 1), + found(6, 5, 4), + found(3, 5, 3), + found(1, 5, 1), + found(5, 1, 1), + OutputSearch { + line: None, + count: Some(0), + rank: None, + continue_from: None, + }, + ], + }, + OutputSearchTestCase { + description: "PostgreSQL output past the chunk budget continues in both directions", + backend: Backend::Postgres, + filler_batches: 70, + searches: vec![ + search("line", 1, forward), + search("line", 66, forward), + search("nomatch", 200, backward), + search("nomatch", 8, backward), + ], + expected_results: vec![ + partial(None, Some(66)), + partial(Some(71), None), + partial(None, Some(8)), + partial(None, None), + ], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (location, claim) = claimed_run(store).await; + let worker = (claim.request.run_id, claim.claim_id); + for number in 0..test_case.filler_batches { + publish_output_batch( + store, + &output, + worker, + batch( + number, + vec![segment( + Some(ORDERS), + out, + &format!("filler {}\n", number + 1), + )], + ), + ) + .await + .expect("filler"); + } + let first = test_case.filler_batches; + for sent in [ + batch( + first, + vec![ + segment(Some(ORDERS), out, "line 1\nline 2\nline 3\n"), + segment( + Some(ORDERS), + err, + "Traceback (most recent call last):\nValueError: bad amount\n", + ), + ], + ), + batch( + first + 1, + vec![segment( + Some(ORDERS), + out, + "line 4\nwarning: slow load\nline 6\n", + )], + ), + ] { + publish_output_batch(store, &output, worker, sent) + .await + .expect("batch"); + } + let (context, admin) = reader(store).await; + let person = ( + (&context, admin), + (location, "development", claim.request.run_id), + DefaultRole::None, + ); + let mut results: Vec = Vec::new(); + for read in &test_case.searches { + let result = search_person_output( + store, + &output, + person, + &OutputSearchQuery { + node: ORDERS.into(), + stream: None, + text: read.text.into(), + from: Some(read.from), + direction: Some(read.direction), + }, + ) + .await + .expect("search") + .expect("run"); + results.push(result); + } + assert_eq!( + results, test_case.expected_results, + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_retention.rs b/crates/sqlbuild-orchestration/tests/run_output/test_retention.rs new file mode 100644 index 0000000000..109d4fb3b5 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_retention.rs @@ -0,0 +1,221 @@ +//! Retention removes a finished run's output objects and index once it is older than `run_output_days`. + +use chrono::TimeDelta; + +use crate::run_output::main::prune_run_output::prune_run_output; +use crate::run_output::main::publish_output_batch::publish_output_batch; +use crate::run_output::models::OutputStream; +#[cfg(unix)] +use crate::run_output::tests::helpers::set_chunks_writable; +use crate::run_output::tests::helpers::{batch, claimed_run, object_count, output_store, segment}; +use crate::run_output::tests::test_types::OutputRetentionTestCase; +#[cfg(unix)] +use crate::run_output::tests::test_types::{OutputRetentionFailureTestCase, RetentionState}; +use crate::runs::tests::helpers::rows; +use crate::store::main::query::query; +use crate::store::main::write::write; +use crate::store::models::Parameter; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_finished_runs_when_retention_runs_then_only_output_past_its_days_is_removed() { + let test_cases = [ + OutputRetentionTestCase { + description: "SQLite run that ended ten days ago", + backend: Backend::Sqlite, + ended_days_ago: Some(10), + expected_pruned: 1, + expected_objects: 0, + expected_marks: 0, + }, + OutputRetentionTestCase { + description: "PostgreSQL run that ended ten days ago", + backend: Backend::Postgres, + ended_days_ago: Some(10), + expected_pruned: 1, + expected_objects: 0, + expected_marks: 0, + }, + OutputRetentionTestCase { + description: "a run that ended yesterday keeps its output", + backend: Backend::Sqlite, + ended_days_ago: Some(1), + expected_pruned: 0, + expected_objects: 2, + expected_marks: 4, + }, + OutputRetentionTestCase { + description: "a running run keeps its output", + backend: Backend::Sqlite, + ended_days_ago: None, + expected_pruned: 0, + expected_objects: 2, + expected_marks: 4, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (_, claim) = claimed_run(store).await; + let run_id = claim.request.run_id; + for number in 0..2_u64 { + publish_output_batch( + store, + &output, + (run_id, claim.claim_id), + batch( + number, + vec![segment( + Some("model:orders"), + OutputStream::Stdout, + "loaded\nerror: a row was refused\nwarning: slow load\n", + )], + ), + ) + .await + .expect("batch"); + } + let days_ago = test_case.ended_days_ago; + write(store, |transaction| async move { + let ended = days_ago.map(|days| transaction.now - TimeDelta::days(days)); + query( + transaction, + "UPDATE sqb_runs SET ended_at=$1 WHERE run_id=$2", + vec![Parameter::OptionalTime(ended), Parameter::Id(run_id)], + ) + .await + }) + .await + .expect("end the run"); + let pruned = prune_run_output(store, &output, 7).await; + assert_eq!( + pruned, test_case.expected_pruned, + "{}", + test_case.description + ); + assert_eq!( + object_count(&output).await, + test_case.expected_objects, + "{}", + test_case.description + ); + let indexed = rows( + store, + "SELECT chunk FROM sqb_run_output_chunks WHERE run_id=$1", + vec![Parameter::Id(run_id)], + ) + .await; + assert_eq!( + indexed.len(), + test_case.expected_objects, + "{}: the index goes with the objects", + test_case.description + ); + let marks = rows( + store, + "SELECT node_line FROM sqb_run_output_marks WHERE run_id=$1", + vec![Parameter::Id(run_id)], + ) + .await; + assert_eq!( + marks.len(), + test_case.expected_marks, + "{}: marked lines go with the index", + test_case.description + ); + assert_eq!( + prune_run_output(store, &output, 7).await, + 0, + "{}: a repeated pass finds nothing", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +/// Read-only folders are how this test makes deletion fail, and they are a unix permission. +#[cfg(unix)] +#[test] +fn given_objects_that_cannot_be_deleted_when_retention_runs_then_the_index_points_at_nothing_and_the_next_pass_finishes() + { + let test_cases = [ + OutputRetentionFailureTestCase { + description: "SQLite run whose objects are read-only at first", + backend: Backend::Sqlite, + expected_states: [(0, 2, 0, 0, 1), (1, 0, 0, 0, 0)], + }, + OutputRetentionFailureTestCase { + description: "PostgreSQL run whose objects are read-only at first", + backend: Backend::Postgres, + expected_states: [(0, 2, 0, 0, 1), (1, 0, 0, 0, 0)], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let folder = tempfile::tempdir().expect("output folder"); + let output = output_store(store, folder.path(), None); + let (_, claim) = claimed_run(store).await; + let run_id = claim.request.run_id; + for number in 0..2_u64 { + publish_output_batch( + store, + &output, + (run_id, claim.claim_id), + batch( + number, + vec![segment( + Some("model:orders"), + OutputStream::Stderr, + "error: a row was refused\n", + )], + ), + ) + .await + .expect("batch"); + } + write(store, |transaction| async move { + let ended = transaction.now - TimeDelta::days(10); + query( + transaction, + "UPDATE sqb_runs SET ended_at=$1 WHERE run_id=$2", + vec![Parameter::Time(ended), Parameter::Id(run_id)], + ) + .await + }) + .await + .expect("end the run"); + let mut states: Vec = Vec::new(); + for writable in [false, true] { + set_chunks_writable(&output, folder.path(), writable).await; + let pruned = prune_run_output(store, &output, 7).await; + let count = + async |sql: &str| rows(store, sql, vec![Parameter::Id(run_id)]).await.len(); + states.push(( + pruned, + object_count(&output).await, + count("SELECT chunk FROM sqb_run_output_chunks WHERE run_id=$1").await, + count("SELECT node_line FROM sqb_run_output_marks WHERE run_id=$1").await, + count("SELECT run_id FROM sqb_run_output WHERE run_id=$1").await, + )); + } + assert_eq!( + states, + test_case.expected_states.to_vec(), + "{}: (pruned, objects, chunks, marks, output rows) after each pass", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_types.rs b/crates/sqlbuild-orchestration/tests/run_output/test_types.rs new file mode 100644 index 0000000000..2668f18cbe --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_types.rs @@ -0,0 +1,152 @@ +use crate::run_output::models::{OutputMark, OutputRow, OutputSearch, SearchDirection}; +use crate::store::tests::store_test_types::Backend; + +/// Where a page starts: forwards from a line, backwards from before one, or from the end. +#[derive(Clone, Copy, Default)] +pub(crate) struct PageStart { + pub(crate) from: Option, + pub(crate) before: Option, + pub(crate) tail: bool, +} + +/// A page to read: node (or the run) and stream, where it starts, and its limit. +pub(crate) struct PageRead { + pub(crate) node: Option<&'static str>, + pub(crate) stream: Option, + pub(crate) start: PageStart, + pub(crate) limit: u32, + pub(crate) expected_rows: Vec, + pub(crate) expected_links: (Option, Option), +} + +pub(crate) struct OutputReadTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// Each node as (node key, lines, stdout lines, stderr lines). + pub(crate) expected_nodes: Vec<(&'static str, i64, i64, i64)>, + pub(crate) expected_run_lines: i64, + pub(crate) expected_marks: Vec, + pub(crate) pages: Vec, + /// The node's whole download, and its stderr alone. + pub(crate) expected_downloads: (&'static str, &'static str), +} + +/// A marked line holding a NUL, in a batch with another line after it and a batch after that. +pub(crate) struct OutputNulTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) printed: [&'static str; 2], + pub(crate) expected_mark: &'static str, + /// Every line as printed, NUL included. + pub(crate) expected_lines: [&'static str; 4], +} + +pub(crate) struct OutputFoldTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) printed: &'static str, + pub(crate) start: PageStart, + pub(crate) limit: u32, + pub(crate) around: Option, + pub(crate) expected_rows: Vec, + pub(crate) expected_span: (i64, i64), +} + +/// One search to run. +pub(crate) struct SearchRead { + pub(crate) text: &'static str, + pub(crate) from: i64, + pub(crate) direction: SearchDirection, +} + +pub(crate) struct OutputSearchTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// How many one-line batches the node prints before the fixture's own lines. + pub(crate) filler_batches: u64, + pub(crate) searches: Vec, + /// What each search finds, in order. + pub(crate) expected_results: Vec, +} + +pub(crate) struct OutputCapTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) max_bytes_per_run: u64, + pub(crate) batches: usize, + /// Each line read back as (number, lines left out just before it). + pub(crate) expected_lines: Vec<(i64, i64)>, + pub(crate) expected_omitted: (i64, i64), + pub(crate) expected_objects: usize, + pub(crate) expected_mark_lines: Vec, +} + +pub(crate) struct OutputRetentionTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) ended_days_ago: Option, + pub(crate) expected_pruned: usize, + pub(crate) expected_objects: usize, + /// Error and warning lines still indexed after the pass. + pub(crate) expected_marks: usize, +} + +pub(crate) struct NodeLogTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) expected_logs: Vec<(&'static str, &'static str, &'static str)>, +} + +pub(crate) struct OutputLargeTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) printed_bytes: usize, + /// The control store's files stay below this many bytes. + pub(crate) expected_control_bytes_below: u64, + pub(crate) expected_tail_lines: usize, +} + +/// What a pass leaves: runs pruned, objects, chunk rows, marks and the run's output row. +#[cfg(unix)] +pub(crate) type RetentionState = (usize, usize, usize, usize, usize); + +#[cfg(unix)] +pub(crate) struct OutputRetentionFailureTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// After a pass that cannot delete the objects, and after the next one that can. + pub(crate) expected_states: [RetentionState; 2], +} + +pub(crate) struct OutputUploadTestCase { + pub(crate) description: &'static str, + /// Each write: the stream and its bytes. + pub(crate) writes: Vec<(crate::run_output::models::OutputStream, Vec)>, + /// Whether the sender has already had a batch refused. + pub(crate) refused_before: bool, + /// Batches queued, the text bytes they hold, and how many replacement characters that text has. + pub(crate) expected_queued: (usize, usize, usize), +} + +pub(crate) struct OutputLocationTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) expected_folder: &'static str, +} + +pub(crate) struct OutputAuditTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// Audit rows after two of each read, by action. + pub(crate) expected_audits: Vec<(&'static str, usize)>, +} + +/// A control store and the user's folders: where output goes with no setting. +pub(crate) struct OutputDefaultTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) state_home: Option<&'static str>, + pub(crate) home: Option<&'static str>, + /// Absolute, or within the SQLite store's folder; `None` when there is no default. + pub(crate) expected_folder: Option<&'static str>, +} diff --git a/crates/sqlbuild-orchestration/tests/run_output/test_upload.rs b/crates/sqlbuild-orchestration/tests/run_output/test_upload.rs new file mode 100644 index 0000000000..1a496a7808 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/run_output/test_upload.rs @@ -0,0 +1,98 @@ +//! A worker's output fits the server's batches, long lines are cut between characters, and a refusal never stops later output. + +use crate::run_output::constants::{MAX_BATCH_SEGMENTS, MAX_BATCH_TEXT_BYTES}; +use crate::run_output::models::{OutputStream, UploadState}; +use crate::run_output::tests::test_types::OutputUploadTestCase; + +#[test] +fn given_large_or_mixed_output_when_batched_then_every_batch_fits_the_server_and_nothing_is_lost() { + let (out, err) = (OutputStream::Stdout, OutputStream::Stderr); + let lines: Vec = "order 1234567 shipped to the north warehouse, row checked\n" + .repeat(9 * 1024 * 1024 / 58) + .into_bytes(); + let long_line: Vec = format!("{}\n", "x".repeat(3 * 1024 * 1024)).into_bytes(); + let accents: Vec = "é".repeat(700_000).into_bytes(); + let test_cases = [ + OutputUploadTestCase { + description: "one 9 MB write of short lines", + writes: vec![(out, lines.clone())], + refused_before: false, + expected_queued: (3, lines.len(), 0), + }, + OutputUploadTestCase { + description: "a 3 MB line is cut into pieces that each end a line", + writes: vec![(out, long_line.clone())], + refused_before: false, + expected_queued: (1, long_line.len() + 2, 0), + }, + OutputUploadTestCase { + description: "a 1.4 MB line of two-byte characters with no newline is cut between characters", + writes: vec![(err, accents.clone())], + refused_before: false, + expected_queued: (1, accents.len() + 2, 0), + }, + OutputUploadTestCase { + description: "ten thousand writes alternating between the streams", + writes: (0..10_000) + .map(|number| ([out, err][number % 2], b"step done\n".to_vec())) + .collect(), + refused_before: false, + expected_queued: (3, 100_000, 0), + }, + OutputUploadTestCase { + description: "output after a refused batch is still taken", + writes: vec![(out, b"after the refusal\n".to_vec())], + refused_before: true, + expected_queued: (1, 18, 0), + }, + ]; + for test_case in test_cases { + let mut state = UploadState::default(); + state.summary.failure = test_case + .refused_before + .then(|| "the control server did not accept run output".to_owned()); + for (stream, bytes) in &test_case.writes { + state.append(("model:orders".into(), *stream), bytes); + } + state.end_lines(); + state.seal(); + let too_big: Vec<(usize, usize)> = state + .queued + .iter() + .map(|batch| { + ( + batch + .segments + .iter() + .map(|segment| segment.text.len()) + .sum(), + batch.segments.len(), + ) + }) + .filter(|(bytes, segments)| { + *bytes > MAX_BATCH_TEXT_BYTES || *segments > MAX_BATCH_SEGMENTS + }) + .collect(); + assert_eq!( + too_big, + Vec::new(), + "{}: batches past the server's limits", + test_case.description + ); + let text: String = state + .queued + .iter() + .flat_map(|batch| batch.segments.iter().map(|segment| segment.text.as_str())) + .collect(); + assert_eq!( + ( + state.queued.len(), + text.len(), + text.matches('\u{FFFD}').count() + ), + test_case.expected_queued, + "{}: (batches, text bytes, replacement characters)", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs b/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs index 114632b912..6549ca86d7 100644 --- a/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs @@ -149,6 +149,8 @@ async fn finish_reporting( node_key: node.clone(), outcome: node_outcome, rows_affected: Some(1), + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/runs/helpers.rs b/crates/sqlbuild-orchestration/tests/runs/helpers.rs index 0627d24316..56739a87ec 100644 --- a/crates/sqlbuild-orchestration/tests/runs/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/runs/helpers.rs @@ -114,6 +114,7 @@ pub(crate) fn request( job_settings: BTreeMap::new(), retry: None, member_attempt: None, + chain_run_id: None, } } diff --git a/crates/sqlbuild-orchestration/tests/runs/test_checks.rs b/crates/sqlbuild-orchestration/tests/runs/test_checks.rs index 3a4d570e86..4b093b7f3a 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_checks.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_checks.rs @@ -248,6 +248,8 @@ fn given_attached_checks_when_a_claim_reports_observations_then_frozen_membershi node_key: "orders".into(), outcome: NodeOutcome::Success, rows_affected: Some(1), + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs b/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs index 5f26a1516b..dfe01dcb34 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs @@ -32,6 +32,8 @@ mod test_groups; mod test_job_detail; #[path = "test_job_subsets.rs"] mod test_job_subsets; +#[path = "test_launch_events.rs"] +mod test_launch_events; #[path = "test_lifecycle.rs"] mod test_lifecycle; #[path = "test_monitor.rs"] @@ -40,6 +42,8 @@ mod test_monitor; mod test_node_errors; #[path = "test_node_event_resources.rs"] mod test_node_event_resources; +#[path = "test_node_results.rs"] +mod test_node_results; #[path = "test_permissions.rs"] mod test_permissions; #[path = "test_pinned_jobs.rs"] diff --git a/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs b/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs index a9ef53cb85..77e4d706ca 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs @@ -34,6 +34,7 @@ fn given_a_member_with_retry_when_it_fails_in_a_group_then_it_retries_inside_the GroupMemberRetryTestCase { description: "SQLite member retry", backend: Backend::Sqlite, + first_outcome: NodeOutcome::Failed, delay_seconds: 900, expected_messages: &[ "staging_job failed, retrying in 15 min (attempt 2 of 3)", @@ -43,6 +44,27 @@ fn given_a_member_with_retry_when_it_fails_in_a_group_then_it_retries_inside_the GroupMemberRetryTestCase { description: "PostgreSQL member retry", backend: Backend::Postgres, + first_outcome: NodeOutcome::Failed, + delay_seconds: 0, + expected_messages: &[ + "staging_job failed, retrying now (attempt 2 of 3)", + "staging_job succeeded on attempt 2", + ], + }, + GroupMemberRetryTestCase { + description: "SQLite member retry of a node its stopped worker cancelled", + backend: Backend::Sqlite, + first_outcome: NodeOutcome::Cancelled, + delay_seconds: 0, + expected_messages: &[ + "staging_job failed, retrying now (attempt 2 of 3)", + "staging_job succeeded on attempt 2", + ], + }, + GroupMemberRetryTestCase { + description: "PostgreSQL member retry of a node its stopped worker cancelled", + backend: Backend::Postgres, + first_outcome: NodeOutcome::Cancelled, delay_seconds: 0, expected_messages: &[ "staging_job failed, retrying now (attempt 2 of 3)", @@ -115,7 +137,7 @@ fn given_a_member_with_retry_when_it_fails_in_a_group_then_it_retries_inside_the .await .expect("claim staging") .expect("staging ready"); - finish(store, &first, (NodeOutcome::Failed, RunOutcome::Failed)).await; + finish(store, &first, (test_case.first_outcome, RunOutcome::Failed)).await; advance_groups(store, &lease, (&limits, scope)) .await .expect("advance after the failure"); @@ -253,5 +275,5 @@ fn given_a_member_with_retry_when_it_fails_in_a_group_then_it_retries_inside_the close_test_store(fixture).await; }); } - assert_eq!(completed, 2, "both backends run"); + assert_eq!(completed, 4, "both backends run"); } diff --git a/crates/sqlbuild-orchestration/tests/runs/test_groups.rs b/crates/sqlbuild-orchestration/tests/runs/test_groups.rs index 8b04fa6921..6123868cf9 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_groups.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_groups.rs @@ -133,6 +133,8 @@ fn given_a_pinned_group_when_redeployed_and_cancelled_then_children_keep_scope_a node_key: "customers".into(), outcome: NodeOutcome::Success, rows_affected: Some(11), + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/runs/test_launch_events.rs b/crates/sqlbuild-orchestration/tests/runs/test_launch_events.rs new file mode 100644 index 0000000000..ac2b3a5dd2 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/runs/test_launch_events.rs @@ -0,0 +1,118 @@ +//! A run's launch event says what started it: a container, or a worker running as a local process. + +use std::collections::BTreeMap; + +use uuid::Uuid; + +use crate::authorization::main::people::bootstrap_user::bootstrap_user; +use crate::credentials::models::{AuditContext, DefaultRole}; +use crate::credentials::tests::location_helpers::create_location; +use crate::runs::constants::RUN_LAUNCHED_EVENT; +use crate::runs::main::execution::change_run::change_run; +use crate::runs::main::execution::claim_next_run::claim_next_run; +use crate::runs::models::{RunAuthority, RunChange, RunChangeRequest}; +use crate::runs::tests::helpers::{queue, request, snapshot}; +use crate::runs::tests::test_types::LaunchEventTestCase; +use crate::scheduler::tests::contracts::helpers::acquire_lease; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::main::migrate_store::migrate_store; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; +use crate::warehouse_history::main::read_person_run_events::read_person_run_events; + +#[test] +fn given_a_launched_run_when_its_events_are_read_then_the_launch_names_a_container_or_a_local_worker() + { + let test_cases = [ + LaunchEventTestCase { + description: "SQLite container", + backend: Backend::Sqlite, + container_id: Some("synthetic-orders-container"), + expected_message: "Container started", + }, + LaunchEventTestCase { + description: "SQLite local process", + backend: Backend::Sqlite, + container_id: None, + expected_message: "Worker started (local process)", + }, + LaunchEventTestCase { + description: "PostgreSQL local process", + backend: Backend::Postgres, + container_id: None, + expected_message: "Worker started (local process)", + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let published = publish_snapshot(store, &snapshot(location)) + .await + .expect("publish"); + queue( + store, + &request((location, published.snapshot_id), 51, 0, &["orders"]), + ) + .await; + let lease = acquire_lease(store, Uuid::now_v7()) + .await + .expect("elect") + .expect("leader"); + let claim = claim_next_run(store, &lease, &BTreeMap::new(), None) + .await + .expect("claim") + .expect("claimable"); + change_run( + store, + RunAuthority::Scheduler(&lease), + &RunChangeRequest { + event_id: Uuid::now_v7(), + run_id: claim.request.run_id, + claim_id: Some(claim.claim_id), + change: RunChange::Launched { + container_id: test_case.container_id.map(str::to_owned), + }, + }, + ) + .await + .expect("launched"); + let context = AuditContext { + actor: "test-operator".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let admin = bootstrap_user(store, &context, "orders-admin") + .await + .expect("administrator"); + let events = read_person_run_events( + store, + (&context, admin), + ((location, "development", claim.request.run_id), (0, 1000)), + DefaultRole::None, + ) + .await + .expect("events") + .expect("run"); + let launched: Vec> = events + .iter() + .filter(|event| event.event_type == RUN_LAUNCHED_EVENT) + .map(|event| event.message.as_deref()) + .collect(); + assert_eq!( + launched, + vec![Some(test_case.expected_message)], + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs b/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs index ac859a9b89..81ad4c2986 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs @@ -245,6 +245,8 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ node_key: node.into(), outcome, rows_affected: Some(17), + table_rows: None, + no_change_reason: None, error_code: (outcome == NodeOutcome::Failed).then(|| "E100".into()), skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs b/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs index 76bb999bc8..e099177ba1 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs @@ -193,3 +193,94 @@ fn given_a_failed_node_when_people_read_its_error_then_only_evidence_on_that_nod }); } } + +#[test] +fn given_a_nul_in_a_failed_nodes_error_when_reported_then_its_failure_and_message_are_recorded() { + let test_cases = [ + RunNodeErrorTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_message: "refused order 17", + }, + RunNodeErrorTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_message: "refused order 17", + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let roles = role_fixture(store).await; + let mut input = snapshot(roles.location_id); + input.generation = 2; + let published = publish_snapshot(store, &input).await.expect("publish"); + queue( + store, + &request( + (roles.location_id, published.snapshot_id), + 1, + 1, + &["orders"], + ), + ) + .await; + let lease = acquire_lease(store, Uuid::now_v7()) + .await + .expect("elect") + .expect("leader"); + let claim = claim_next_run(store, &lease, &BTreeMap::new(), None) + .await + .expect("claim") + .expect("queued run"); + let run_id = claim.request.run_id; + for change in [ + json!({"kind": "started"}), + json!({"kind": "node_finished", "node_key": "orders", "outcome": "failed", + "rows_affected": null, "error_code": "X000", "skipped_because_of": null, + "error_message": "refused \0order 17"}), + ] { + let reported: RunChangeRequest = serde_json::from_value(json!({ + "event_id": Uuid::now_v7(), "run_id": run_id, + "claim_id": claim.claim_id, "change": change, + })) + .expect("a worker's report body"); + let authority = RunAuthority::Worker { + run_id, + claim_id: claim.claim_id, + }; + change_run(store, authority, &reported) + .await + .unwrap_or_else(|error| { + panic!("{}: the report was refused: {error}", test_case.description) + }); + } + let nodes = rows( + store, + "SELECT status FROM sqb_run_nodes WHERE run_id=$1 AND node_key='orders'", + vec![Parameter::Id(run_id)], + ) + .await; + let error = read_person_run_node_error( + store, + (&roles.context, credentials(&roles.administrator)), + (roles.location_id, "development"), + (run_id, "orders"), + ) + .await + .expect("administrator") + .expect("orders ran"); + assert_eq!( + (nodes[0]["status"].as_str(), error.message.as_deref()), + (Some("failed"), Some(test_case.expected_message)), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs b/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs index 0757f3562b..39b4ab1f88 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs @@ -11,7 +11,7 @@ use crate::credentials::tests::location_helpers::create_location; use crate::runs::main::execution::{change_run::change_run, claim_next_run::claim_next_run}; use crate::runs::models::{NodeOutcome, RunAuthority, RunChange, RunChangeRequest}; use crate::runs::tests::helpers::{queue, request, snapshot, snapshot_node}; -use crate::runs::tests::test_types::{NodeEventResourcesTestCase, NodeOfTestCase}; +use crate::runs::tests::test_types::{CheckFields, NodeEventResourcesTestCase, NodeOfTestCase}; use crate::scheduler::tests::contracts::helpers::acquire_lease; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; use crate::store::main::{begin::begin, commit::commit, query::query}; @@ -42,6 +42,12 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n ("run_check_finished", "check", "payments_positive"), ("run_node_finished", "model", "payments"), ], + expected_check: ( + Some("payments_positive".into()), + Some("b-payments-positive".into()), + Some("r-1".into()), + Some(14), + ), }, NodeEventResourcesTestCase { description: "PostgreSQL node and check events", @@ -52,6 +58,12 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n ("run_check_finished", "check", "payments_positive"), ("run_node_finished", "model", "payments"), ], + expected_check: ( + Some("payments_positive".into()), + Some("b-payments-positive".into()), + Some("r-1".into()), + Some(14), + ), }, ]; for test_case in test_cases { @@ -102,20 +114,23 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n let node_started = report(RunChange::NodeStarted { node_key: "model:payments".into(), }); + let check_finished = report(RunChange::CheckFinished { + node_key: "check:payments_positive".into(), + outcome: NodeOutcome::Success, + }); for request in [ report(RunChange::Started), node_started.clone(), report(RunChange::CheckStarted { node_key: "check:payments_positive".into(), }), - report(RunChange::CheckFinished { - node_key: "check:payments_positive".into(), - outcome: NodeOutcome::Success, - }), + check_finished.clone(), report(RunChange::NodeFinished { node_key: "model:payments".into(), outcome: NodeOutcome::Success, rows_affected: Some(3), + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, @@ -216,6 +231,54 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n "{}: the old event is named from its payload", test_case.description ); + + // A check's result, as the worker records it: its name, identity and rows come from its payload. + let transaction = begin(store, TransactionMode::Write).await.expect("begin"); + let (transaction, _) = query( + transaction, + "UPDATE recall_events SET event_type='audit_completed', outcome='warn', payload=$1 WHERE event_id=$2", + vec![ + Parameter::Json(json!({ + "audit_name": "payments_positive", + "binding_key": "b-payments-positive", + "result_id": "r-1", + "outcome": "warn", + "violation_count": 14, + "executed_sql": "SELECT 1", + })), + Parameter::Text(check_finished.event_id.to_string()), + ], + ) + .await + .expect("store a check result"); + commit(transaction).await.expect("commit"); + let events = read_person_run_events( + store, + (&context, admin), + ((location, "development", claim.request.run_id), (0, 1000)), + DefaultRole::None, + ) + .await + .expect("run events") + .expect("run"); + let checks: Vec = events + .iter() + .filter(|event| event.event_type == "audit_completed") + .map(|event| { + ( + event.check_name.clone(), + event.check_binding_key.clone(), + event.check_result_id.clone(), + event.check_rows, + ) + }) + .collect(); + assert_eq!( + checks, + vec![test_case.expected_check.clone()], + "{}: a check result names its check and the rows it found, never its SQL", + test_case.description + ); close_test_store(fixture).await; }); } diff --git a/crates/sqlbuild-orchestration/tests/runs/test_node_results.rs b/crates/sqlbuild-orchestration/tests/runs/test_node_results.rs new file mode 100644 index 0000000000..34d2203685 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/runs/test_node_results.rs @@ -0,0 +1,321 @@ +//! A run's node list says what each node did: its materialization, the rows it added or the table now holds, its progress, why it changed nothing, and which nodes never ran. + +use std::collections::BTreeMap; + +use serde_json::json; +use uuid::Uuid; + +use crate::credentials::tests::location_helpers::create_location; +use crate::runs::main::execution::change_run::change_run; +use crate::runs::main::execution::claim_next_run::claim_next_run; +use crate::runs::main::listings::list_run_nodes::list_run_nodes; +use crate::runs::models::{NodeOutcome, RunAuthority, RunChange, RunChangeRequest}; +use crate::runs::tests::helpers::{queue, request, rows, snapshot}; +use crate::runs::tests::test_types::{MissingSecretNodesTestCase, NodeResultsTestCase}; +use crate::scheduler::tests::contracts::helpers::acquire_lease; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::Parameter; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +const EXPECTED_NODES: &[crate::runs::tests::test_types::NodeResultRow] = &[ + ( + "customers", + "success", + Some("incremental"), + (Some(48), None, None), + None, + ), + ( + "inventory", + "not_run", + Some("table"), + (None, None, None), + None, + ), + ( + "orders", + "success", + Some("table"), + (None, Some(500), Some(120)), + None, + ), + ( + "products", + "success", + Some("view"), + (None, None, None), + Some("unchanged since its last build"), + ), +]; + +/// Redaction takes the first variable after a provider named like a secret, and the provider stays readable. +const EXPECTED_SECRET_NODES: &[(&str, Option<&str>)] = &[ + ( + "customers", + Some( + "provider region: REGION_CODE not set (missing from the location's environment and from config/production.env)", + ), + ), + ("inventory", None), + ( + "orders", + Some( + "provider orders_api_key: [REDACTED], ORDERS_REGION not set (missing from the location's environment)", + ), + ), + ("products", None), +]; + +#[test] +fn given_a_run_reporting_what_each_node_did_when_its_nodes_are_listed_then_rows_progress_no_change_and_not_run_read_back() + { + let test_cases = [ + NodeResultsTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_nodes: EXPECTED_NODES, + expected_not_run: 1, + }, + NodeResultsTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_nodes: EXPECTED_NODES, + expected_not_run: 1, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let mut input = snapshot(location); + for (key, materialization) in [ + ("customers", "incremental"), + ("inventory", "table"), + ("orders", "table"), + ("products", "view"), + ] { + input.nodes.get_mut(key).expect("node").definition = + json!({"materialization": materialization}); + } + let published = publish_snapshot(store, &input).await.expect("publish"); + let pinned = request( + (location, published.snapshot_id), + 41, + 0, + &["customers", "inventory", "orders", "products"], + ); + queue(store, &pinned).await; + let lease = acquire_lease(store, Uuid::now_v7()) + .await + .expect("elect") + .expect("leader"); + let claim = claim_next_run(store, &lease, &BTreeMap::new(), None) + .await + .expect("claim") + .expect("claimable"); + let finished = + |node: &str, outcome, (rows_affected, table_rows), reason: Option<&str>| { + RunChange::NodeFinished { + node_key: node.into(), + outcome, + rows_affected, + table_rows, + no_change_reason: reason.map(str::to_owned), + error_code: None, + skipped_because_of: None, + error_message: None, + } + }; + for change in [ + RunChange::Started, + RunChange::NodeStarted { + node_key: "orders".into(), + }, + RunChange::NodeProgress { + node_key: "orders".into(), + rows_so_far: 120, + }, + finished("orders", NodeOutcome::Success, (None, Some(500)), None), + finished("customers", NodeOutcome::Success, (Some(48), None), None), + finished( + "products", + NodeOutcome::Success, + (None, None), + Some("unchanged since its last build"), + ), + finished("inventory", NodeOutcome::NotRun, (None, None), None), + ] { + change_run( + store, + RunAuthority::Worker { + run_id: claim.request.run_id, + claim_id: claim.claim_id, + }, + &RunChangeRequest { + event_id: Uuid::now_v7(), + run_id: claim.request.run_id, + claim_id: Some(claim.claim_id), + change, + }, + ) + .await + .expect("worker fact"); + } + let nodes: Vec<_> = list_run_nodes(store, claim.request.run_id) + .await + .expect("nodes") + .into_iter() + .map(|node| { + ( + node.node_key, + node.status, + node.materialization, + (node.rows_affected, node.table_rows, node.rows_so_far), + node.no_change_reason, + ) + }) + .collect(); + let expected: Vec<_> = test_case + .expected_nodes + .iter() + .map(|(key, status, materialization, counts, reason)| { + ( + (*key).to_owned(), + (*status).to_owned(), + materialization.map(str::to_owned), + *counts, + reason.map(str::to_owned), + ) + }) + .collect(); + assert_eq!(nodes, expected, "{}", test_case.description); + let counts = rows( + store, + "SELECT node_counts_json FROM sqb_runs WHERE run_id=$1", + vec![Parameter::Id(claim.request.run_id)], + ) + .await; + assert_eq!( + crate::runs::tests::helpers::json_column(&counts[0]["node_counts_json"])["not_run"], + json!(test_case.expected_not_run), + "{}: the run counts nodes it never reached apart from skips", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_nodes_failed_for_missing_secrets_when_listed_then_only_those_unstarted_carry_their_message() + { + let test_cases = [ + MissingSecretNodesTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_nodes: EXPECTED_SECRET_NODES, + }, + MissingSecretNodesTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_nodes: EXPECTED_SECRET_NODES, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let published = publish_snapshot(store, &snapshot(location)) + .await + .expect("publish"); + let pinned = request( + (location, published.snapshot_id), + 42, + 0, + &["customers", "inventory", "orders", "products"], + ); + queue(store, &pinned).await; + let lease = acquire_lease(store, Uuid::now_v7()) + .await + .expect("elect") + .expect("leader"); + let claim = claim_next_run(store, &lease, &BTreeMap::new(), None) + .await + .expect("claim") + .expect("claimable"); + let failed = |node: &str, message: &str| { + json!({"kind": "node_finished", "node_key": node, "outcome": "failed", + "rows_affected": null, "error_code": "D012", "skipped_because_of": null, + "error_message": message}) + }; + for change in [ + json!({"kind": "started"}), + failed( + "customers", + "provider region: REGION_CODE not set (missing from the location's environment and from config/production.env)", + ), + failed( + "orders", + "provider orders_api_key: ORDERS_API_KEY, ORDERS_REGION not set (missing from the location's environment)", + ), + failed( + "inventory", + "Provider 'inventory' has invalid settings: input_value='north'", + ), + json!({"kind": "node_started", "node_key": "products"}), + failed( + "products", + "provider catalog: north not set (missing from a node's own error)", + ), + ] { + let reported: RunChangeRequest = serde_json::from_value(json!({ + "event_id": Uuid::now_v7(), "run_id": claim.request.run_id, + "claim_id": claim.claim_id, "change": change, + })) + .expect("a worker's report body"); + change_run( + store, + RunAuthority::Worker { + run_id: claim.request.run_id, + claim_id: claim.claim_id, + }, + &reported, + ) + .await + .expect("worker fact"); + } + + let nodes: Vec<(String, Option)> = list_run_nodes(store, claim.request.run_id) + .await + .expect("nodes") + .into_iter() + .map(|node| (node.node_key, node.missing_secret)) + .collect(); + + let listed: Vec<(&str, Option<&str>)> = nodes + .iter() + .map(|(key, message)| (key.as_str(), message.as_deref())) + .collect(); + assert_eq!( + listed, test_case.expected_nodes, + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs b/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs index 214fdd53e1..a3f77fe773 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs @@ -22,15 +22,14 @@ use crate::credentials::tests::location_helpers::create_location; use crate::runs::tests::claim_helpers::{slot_counts, succeed}; use crate::runs::tests::helpers::snapshot; use crate::runs::tests::test_types::{ - RerunExecutionTestCase, RunLifecycleTestCase, TransactionFault, + CancelledRerunTestCase, RerunExecutionTestCase, RunLifecycleTestCase, TransactionFault, }; use crate::store::tests::fault_helpers::{install_fault, remove_fault}; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store::tests::store_test_types::Backend; #[test] -fn given_a_partial_group_when_rerun_after_redeploy_then_only_failed_and_skipped_nodes_retry_atomically() - { +fn given_a_partial_group_when_rerun_after_redeploy_then_only_unfinished_nodes_retry_atomically() { let test_cases = [ RunLifecycleTestCase { description: "SQLite pinned group rerun", @@ -164,6 +163,8 @@ fn given_a_partial_group_when_rerun_after_redeploy_then_only_failed_and_skipped_ node_key: node.clone(), outcome, rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: (outcome == NodeOutcome::Skipped) .then(|| "orders".into()), @@ -263,10 +264,12 @@ fn given_a_partial_group_when_rerun_after_redeploy_then_only_failed_and_skipped_ ]); for execution in [ RerunExecutionTestCase { - description: "failure retry omits successful and cancelled nodes", + description: "failure retry omits only successful nodes", request: retry.clone(), expected_applied: false, - expected_selection: ["orders", "inventory"].map(str::to_owned).into(), + expected_selection: ["orders", "inventory", "customers"] + .map(str::to_owned) + .into(), expected_jobs: &["staging", "marts"], }, RerunExecutionTestCase { @@ -337,6 +340,11 @@ fn given_a_partial_group_when_rerun_after_redeploy_then_only_failed_and_skipped_ ); assert_eq!(claim.request.origin, RunOrigin::Rerun); assert_eq!(claim.request.priority, 7); + assert_eq!( + claim.request.chain_run_id, + Some(Uuid::new_v5(&source_id, expected_job.as_bytes())), + "a rerun's member run keeps the first run of its own chain: the source's member" + ); assert_eq!(claim.request.settings, settings[expected_job]); assert_eq!( claim.request.window, @@ -389,3 +397,212 @@ fn given_a_partial_group_when_rerun_after_redeploy_then_only_failed_and_skipped_ }); } } + +#[test] +fn given_cancelled_nodes_when_rerunning_from_failure_then_every_unfinished_node_runs_and_only_uncancelled_runs_retry() + { + let test_cases = [ + CancelledRerunTestCase { + description: "a person cancels mid-chain", + outcomes: [ + NodeOutcome::Success, + NodeOutcome::Cancelled, + NodeOutcome::Cancelled, + ], + run_outcome: RunOutcome::Cancelled, + cancel_requests: 1, + expected_retried: vec![], + expected_rerun: vec!["inventory", "orders"], + }, + CancelledRerunTestCase { + description: "a person cancels after a failure", + outcomes: [ + NodeOutcome::Success, + NodeOutcome::Failed, + NodeOutcome::Cancelled, + ], + run_outcome: RunOutcome::Partial, + cancel_requests: 1, + expected_retried: vec![], + expected_rerun: vec!["inventory", "orders"], + }, + CancelledRerunTestCase { + description: "a failed run nobody cancelled retries its cancelled node too", + outcomes: [ + NodeOutcome::Failed, + NodeOutcome::Cancelled, + NodeOutcome::Cancelled, + ], + run_outcome: RunOutcome::Failed, + cancel_requests: 0, + expected_retried: vec!["customers", "inventory", "orders"], + expected_rerun: vec!["customers", "inventory", "orders"], + }, + CancelledRerunTestCase { + description: "a partial run nobody cancelled retries failed and cancelled nodes", + outcomes: [ + NodeOutcome::Success, + NodeOutcome::Failed, + NodeOutcome::Cancelled, + ], + run_outcome: RunOutcome::Partial, + cancel_requests: 0, + expected_retried: vec!["inventory", "orders"], + expected_rerun: vec!["inventory", "orders"], + }, + CancelledRerunTestCase { + description: "a stopped worker with only cancelled nodes left retries them", + outcomes: [ + NodeOutcome::Success, + NodeOutcome::Cancelled, + NodeOutcome::Cancelled, + ], + run_outcome: RunOutcome::Partial, + cancel_requests: 0, + expected_retried: vec!["inventory", "orders"], + expected_rerun: vec!["inventory", "orders"], + }, + ]; + for test_case in test_cases { + for backend in [Backend::Sqlite, Backend::Postgres] { + run(async { + let Some(fixture) = open_test_store(backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let context = AuditContext { + actor: "test-operator".into(), + granting_role: "control-store-owner".into(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let mut input = snapshot(location); + input.documents.insert( + "jobs".into(), + json!({"chain": {"description": "Build the chain", + "selection": ["customers", "inventory", "orders"], + "on_failure": {"retries": 1, "retry_delay_seconds": 0}}}), + ); + publish_snapshot(store, &input).await.expect("publish"); + let lease = acquire_lease(store, Uuid::now_v7()) + .await + .expect("elect") + .expect("leader"); + let source_id = Uuid::now_v7(); + request_job_run( + store, + (&context, None), + &JobRunRequest { + run_id: source_id, + location_id: location, + target: "development".into(), + job_key: "chain".into(), + reason: "Build the chain".into(), + priority: 0, + window: None, + full_refresh: false, + select: Vec::new(), + exclude: Vec::new(), + }, + ) + .await + .expect("request the chain"); + let limits = BTreeMap::new(); + let scope = (location, "development"); + let source = claim_next_run(store, &lease, &limits, Some(scope)) + .await + .expect("claim") + .expect("source run"); + let worker = || RunAuthority::Worker { + run_id: source_id, + claim_id: source.claim_id, + }; + let change = |claim_id, change| RunChangeRequest { + event_id: Uuid::now_v7(), + run_id: source_id, + claim_id, + change, + }; + let claimed = Some(source.claim_id); + change_run(store, worker(), &change(claimed, RunChange::Started)) + .await + .expect("start"); + for _ in 0..test_case.cancel_requests { + let requested = RunChange::CancelRequested { + actor: "test-operator".into(), + reason: "Stop".into(), + }; + change_run( + store, + RunAuthority::Operator(&context), + &change(None, requested), + ) + .await + .expect("cancel"); + } + for (node, outcome) in source.request.selection.iter().zip(test_case.outcomes) { + let finished = RunChange::NodeFinished { + node_key: node.clone(), + outcome, + rows_affected: None, + table_rows: None, + no_change_reason: None, + error_code: None, + skipped_because_of: None, + error_message: None, + }; + change_run(store, worker(), &change(claimed, finished)) + .await + .expect("finish a node"); + } + let ended = RunChange::Finished { + outcome: test_case.run_outcome, + reason: "synthetic worker exit".into(), + exit_code: Some(1), + }; + change_run(store, worker(), &change(claimed, ended)) + .await + .expect("finish the run"); + let retried: Vec = claim_next_run(store, &lease, &limits, Some(scope)) + .await + .expect("look for a retry") + .map(|retry| retry.request.selection.into_iter().collect()) + .unwrap_or_default(); + assert_eq!( + retried, test_case.expected_retried, + "{}", + test_case.description + ); + let rerun = RerunRequest { + run_id: Uuid::now_v7(), + source_run_id: source_id, + from_failure: true, + reason: "Finish the chain".into(), + priority: 0, + nodes: Vec::new(), + }; + request_rerun(store, (&context, None), &rerun) + .await + .expect("rerun from failure"); + let requested = list_runs(store, scope, 20) + .await + .expect("list") + .into_iter() + .find(|run| run.run_id == rerun.run_id) + .expect("the rerun"); + let selection: BTreeSet<&str> = requested + .selection_json + .iter() + .map(String::as_str) + .collect(); + let expected: BTreeSet<&str> = test_case.expected_rerun.iter().copied().collect(); + assert_eq!(selection, expected, "{}", test_case.description); + close_test_store(fixture).await; + }); + } + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_retries.rs b/crates/sqlbuild-orchestration/tests/runs/test_retries.rs index 2fe527cf05..fee7bb50e3 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_retries.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_retries.rs @@ -127,6 +127,12 @@ fn given_a_job_with_on_failure_when_its_runs_fail_then_retries_rerun_failed_work "{}: each retry reruns the run before it", test_case.description ); + assert_eq!( + [&retry_one, &retry_two].map(|claim| claim.request.chain_run_id), + [Some(source.run_id), Some(source.run_id)], + "{}: every retry keeps the first run of the chain as its root", + test_case.description + ); assert_eq!( [&retry_one, &retry_two] .map(|claim| claim.request.retry.as_ref().map(|retry| retry.attempt)) diff --git a/crates/sqlbuild-orchestration/tests/runs/test_types.rs b/crates/sqlbuild-orchestration/tests/runs/test_types.rs index aad00bc8dc..77f93fcf0a 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_types.rs @@ -5,7 +5,7 @@ use std::collections::BTreeSet; use uuid::Uuid; use crate::credentials::models::BuiltinRole; -use crate::runs::models::{RerunRequest, RunOrigin, RunStatus}; +use crate::runs::models::{NodeOutcome, RerunRequest, RunOrigin, RunOutcome, RunStatus}; pub(crate) use crate::store::tests::fault_types::TransactionFault; use crate::store::tests::store_test_types::Backend; @@ -443,6 +443,8 @@ pub(crate) struct GroupDependencyTestCase { } pub(crate) struct GroupMemberRetryTestCase { + /// How the member's node ended the attempt that retries. + pub(crate) first_outcome: crate::runs::models::NodeOutcome, pub(crate) description: &'static str, pub(crate) backend: Backend, /// The failing member's `retry_delay_seconds`. @@ -561,8 +563,13 @@ pub(crate) struct NodeEventResourcesTestCase { pub(crate) backend: Backend, /// Each node and check event's type, resource kind and resource name, in the order they happened. pub(crate) expected_named: [(&'static str, &'static str, &'static str); 4], + /// The check result's name, check ID, result ID and rows found, as the run's events report them. + pub(crate) expected_check: CheckFields, } +/// A check result's name, check ID, result ID and rows found. +pub(crate) type CheckFields = (Option, Option, Option, Option); + pub(crate) struct NodeOfTestCase { pub(crate) description: &'static str, /// The node identity columns a run's events read selects from an event's payload. @@ -577,3 +584,45 @@ pub(crate) struct StoredRequestTestCase { /// The source's claim, its retry's origin, its person rerun's status and the rerun's cancellation. pub(crate) expected_outcomes: (bool, RunOrigin, RunStatus, RunStatus), } + +/// One run node as the run's node list reads it back. +pub(crate) type NodeResultRow = ( + &'static str, + &'static str, + Option<&'static str>, + (Option, Option, Option), + Option<&'static str>, +); + +pub(crate) struct NodeResultsTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// Each node's key, status, materialization, (rows affected, table rows, rows so far) and why it changed nothing. + pub(crate) expected_nodes: &'static [NodeResultRow], + pub(crate) expected_not_run: i64, +} + +/// What a run's node list tells each of its failed nodes about a missing secret. +pub(crate) struct MissingSecretNodesTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) expected_nodes: &'static [(&'static str, Option<&'static str>)], +} + +pub(crate) struct LaunchEventTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) container_id: Option<&'static str>, + pub(crate) expected_message: &'static str, +} + +pub(crate) struct CancelledRerunTestCase { + pub(crate) description: &'static str, + /// The outcomes of `customers`, `inventory` and `orders`, in that order. + pub(crate) outcomes: [NodeOutcome; 3], + pub(crate) run_outcome: RunOutcome, + /// How many times a person asked to cancel the run. + pub(crate) cancel_requests: usize, + pub(crate) expected_retried: Vec<&'static str>, + pub(crate) expected_rerun: Vec<&'static str>, +} diff --git a/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs b/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs index ff9f72f2e2..3b5a141a10 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs @@ -249,6 +249,8 @@ pub(crate) async fn report_run( node_key: node_key.clone(), outcome: node, rows_affected: Some(1), + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs b/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs index 933efddd78..c3ce2e79b1 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs @@ -123,7 +123,9 @@ fn given_jobs_published_before_0004_when_migrating_then_plain_job_runs_work_and_ ] }; - migrate_store(store).await.expect("migrate to version 4"); + migrate_with(store, &MIGRATIONS[..3]) + .await + .expect("migrate to version 4"); let stored = rows( store, "SELECT definition_json FROM sqb_jobs WHERE job_key='orders'", @@ -233,7 +235,9 @@ fn given_a_group_schedule_published_before_0004_when_the_scheduler_cycles_then_o publish_snapshot(store, &input).await.expect("publish"); store_old_job_definitions(store, test_case.stored_source).await; store_old_documents(store, test_case.stored_source).await; - migrate_store(store).await.expect("migrate to version 4"); + migrate_with(store, &MIGRATIONS[..3]) + .await + .expect("migrate to version 4"); let other = create_location(store, "returns", "test-admin") .await .expect("another location"); @@ -331,7 +335,9 @@ fn given_a_job_published_before_0004_when_its_run_fails_before_a_republish_then_ publish_snapshot(store, &input).await.expect("publish"); store_old_job_definitions(store, test_case.stored_source).await; store_old_documents(store, test_case.stored_source).await; - migrate_store(store).await.expect("migrate to version 4"); + migrate_with(store, &MIGRATIONS[..3]) + .await + .expect("migrate to version 4"); request_job_run(store, (&operator(), None), &manual_run(location, "orders")) .await .expect("a manual run of the migrated job"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/helpers.rs b/crates/sqlbuild-orchestration/tests/sensors/helpers.rs index 352f04583d..af28222321 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/helpers.rs @@ -12,7 +12,8 @@ use crate::runs::main::{ execution::claim_next_run::claim_next_run, requests::request_job_run::request_job_run, }; use crate::runs::models::{ - JobRunRequest, NodeOutcome, RunAuthority, RunChange, RunChangeRequest, RunOutcome, + JobRunRequest, NodeOutcome, RunAuthority, RunChange, RunChangeRequest, RunCommand, RunKind, + RunOutcome, RunRequest, }; use crate::scheduler::models::SchedulerLease; use crate::sensors::main::complete_sensor::complete_sensor; @@ -27,6 +28,7 @@ use crate::store::main::query::query; use crate::store::models::{ControlEvent, ControlStore, Parameter, TransactionMode}; use crate::runs::tests::helpers::snapshot as base_snapshot; +use crate::runs::tests::helpers::{json_column, rows}; /// Ticks a drain runs: more than any test has events, so each is delivered and the cursor reaches the end. const DRAIN_TICKS: usize = 160; @@ -216,6 +218,30 @@ pub(crate) async fn finish_claimed_run( .await; } +/// Store a run as the ad-hoc run of `command` a worker would have executed. +pub(crate) async fn record_as_adhoc(store: &ControlStore, run_id: Uuid, command: RunCommand) { + let stored = rows( + store, + "SELECT request_json FROM sqb_runs WHERE run_id=$1", + vec![Parameter::Id(run_id)], + ) + .await + .remove(0); + let mut request: RunRequest = + serde_json::from_value(json_column(&stored["request_json"])).expect("stored request"); + request.kind = RunKind::Adhoc; + request.job_key = None; + request.command = command; + let (transaction, _) = query( + begin(store, TransactionMode::Write).await.expect("write"), + "UPDATE sqb_runs SET kind='adhoc',job_key=NULL,request_json=$1 WHERE run_id=$2", + vec![Parameter::Json(json!(request)), Parameter::Id(run_id)], + ) + .await + .expect("ad-hoc run"); + commit(transaction).await.expect("commit"); +} + /// Request a run of `job_key` and finish it with `outcome`, its nodes succeeding and each attached check ending as given. pub(crate) async fn finish_run_with_checks( store: &ControlStore, @@ -270,6 +296,8 @@ async fn finish_checked_run( node_key: key.into(), outcome: nodes[index], rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, @@ -328,6 +356,8 @@ pub(crate) fn node_finished(node_key: &str, outcome: NodeOutcome) -> RunChange { node_key: node_key.into(), outcome, rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs b/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs index cf2fe4be1e..2f7019adf6 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs @@ -8,9 +8,11 @@ use uuid::Uuid; use crate::credentials::tests::location_helpers::create_location; use crate::declarations::main::list_triggers::list_triggers; use crate::runs::main::listings::list_runs::list_runs; -use crate::runs::models::{NodeOutcome, RunOutcome, RunStatus}; +use crate::runs::models::{NodeOutcome, RunCommand, RunOutcome, RunStatus}; use crate::scheduler::tests::contracts::helpers::acquire_lease; -use crate::sensors::tests::helpers::{drain_sensor, finish_run_with_checks, snapshot}; +use crate::sensors::tests::helpers::{ + drain_sensor, finish_run_with_checks, record_as_adhoc, snapshot, +}; use crate::sensors::tests::test_types::CheckEventTestCase; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; use crate::store::main::{ @@ -28,21 +30,56 @@ fn given_a_successful_run_with_a_failed_check_and_a_warned_audit_when_a_check_se description: "SQLite failures and warnings", backend: Backend::Sqlite, kinds: &["failed", "warn"], - run_kind: "job", + adhoc_command: &[], expected_checks: &["audit:orders_amount", "check:orders_valid"], }, CheckEventTestCase { description: "PostgreSQL failures only", backend: Backend::Postgres, kinds: &["failed"], - run_kind: "job", + adhoc_command: &[], expected_checks: &["check:orders_valid"], }, CheckEventTestCase { - description: "SQLite: an ad-hoc test or audit run is a development command, not an event", + description: "SQLite: a manual build is watched like a job run", + backend: Backend::Sqlite, + kinds: &["failed", "warn"], + adhoc_command: &[RunCommand::Build], + expected_checks: &["audit:orders_amount", "check:orders_valid"], + }, + CheckEventTestCase { + description: "SQLite: a standalone test run is not an event", + backend: Backend::Sqlite, + kinds: &["failed", "warn"], + adhoc_command: &[RunCommand::Test], + expected_checks: &[], + }, + CheckEventTestCase { + description: "SQLite: a standalone audit run is not an event", backend: Backend::Sqlite, kinds: &["failed", "warn"], - run_kind: "adhoc", + adhoc_command: &[RunCommand::Audit], + expected_checks: &[], + }, + CheckEventTestCase { + description: "PostgreSQL: a manual build is watched like a job run", + backend: Backend::Postgres, + kinds: &["failed", "warn"], + adhoc_command: &[RunCommand::Build], + expected_checks: &["audit:orders_amount", "check:orders_valid"], + }, + CheckEventTestCase { + description: "PostgreSQL: a standalone test run is not an event", + backend: Backend::Postgres, + kinds: &["failed", "warn"], + adhoc_command: &[RunCommand::Test], + expected_checks: &[], + }, + CheckEventTestCase { + description: "PostgreSQL: a standalone audit run is not an event", + backend: Backend::Postgres, + kinds: &["failed", "warn"], + adhoc_command: &[RunCommand::Audit], expected_checks: &[], }, ]; @@ -95,17 +132,9 @@ fn given_a_successful_run_with_a_failed_check_and_a_warned_audit_when_a_check_se ], ) .await; - let (transaction, _) = query( - begin(store, TransactionMode::Write).await.expect("write"), - "UPDATE sqb_runs SET kind=$2 WHERE run_id=$1", - vec![ - Parameter::Id(source), - Parameter::Text(test_case.run_kind.into()), - ], - ) - .await - .expect("run kind"); - commit(transaction).await.expect("commit"); + for command in test_case.adhoc_command { + record_as_adhoc(store, source, *command).await; + } assert_eq!( drain_sensor(store, &lease, trigger.trigger_id).await, test_case.expected_checks.len(), diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs b/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs index cfc4934769..096e404e0f 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs @@ -38,5 +38,7 @@ mod test_sources; mod test_transitions; #[path = "test_types.rs"] mod test_types; +#[path = "test_unreadable_ticks.rs"] +mod test_unreadable_ticks; #[path = "test_upgrade.rs"] mod test_upgrade; diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs b/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs index f8f4aceb1c..e5399d2570 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs @@ -1,5 +1,6 @@ //! A polling sensor's function answers over the real outbound HTTP boundary, which returns data, never scheduler authority. +use crate::platform::models::LocationWorkScope; use std::time::Duration; use chrono::{TimeDelta, Utc}; @@ -94,6 +95,7 @@ fn given_custom_sensor_work_when_results_retry_then_cursor_runs_and_outcome_comm let poll = LocationWorkPoll { session_id: Uuid::now_v7(), target: "development".into(), + scope: LocationWorkScope::All, }; report_location_health( store, @@ -336,7 +338,7 @@ fn given_custom_sensor_work_when_results_retry_then_cursor_runs_and_outcome_comm CustomSensorResultCase { outcome: SensorFunctionOutcome::Failed { error: - "Traceback (most recent call last):\nValueError: orders feed is down" + "Traceback (most recent call last):\nValueError: orders \0feed is down" .into(), }, expected_phase: "failed", @@ -392,6 +394,11 @@ fn given_custom_sensor_work_when_results_retry_then_cursor_runs_and_outcome_comm let outcome = &facts.last().expect("terminal evaluation phase").outcome; assert_eq!(outcome.phase(), result_case.expected_phase); let payload = serde_json::to_value(outcome).expect("outcome payload"); + assert!( + !payload.to_string().contains("\\u0000"), + "{}: a traceback is stored without NUL", + test_case.description + ); assert_eq!( payload["cursor"]["custom"].as_str(), result_case.expected_cursor diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs b/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs index 4a2a155f79..8ca6a7f377 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs @@ -131,6 +131,8 @@ fn given_a_wide_group_when_only_the_last_node_has_not_started_then_all_chunks_mu node_key: key.clone(), outcome: NodeOutcome::Success, rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs b/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs index 52e1e3ef46..1e2a59d2c9 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs @@ -205,6 +205,8 @@ fn given_any_run_rebuilds_when_consuming_then_only_genuine_scoped_successes_queu node_key: "orders".into(), outcome: NodeOutcome::Success, rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, @@ -296,6 +298,8 @@ fn given_any_run_rebuilds_when_consuming_then_only_genuine_scoped_successes_queu node_key: "customers".into(), outcome: NodeOutcome::Success, rows_affected: None, + table_rows: None, + no_change_reason: None, error_code: None, skipped_because_of: None, error_message: None, diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_types.rs b/crates/sqlbuild-orchestration/tests/sensors/test_types.rs index fe5cd99577..8498170cbf 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_types.rs @@ -49,8 +49,8 @@ pub(crate) struct CheckEventTestCase { pub(crate) backend: Backend, /// The `check_event` kinds the sensor watches. pub(crate) kinds: &'static [&'static str], - /// The watched run's kind: `job`, or `adhoc` as a worker's `sqb test` or `sqb audit` run is. - pub(crate) run_kind: &'static str, + /// The command of an ad-hoc watched run; empty watches a job's run. + pub(crate) adhoc_command: &'static [crate::runs::models::RunCommand], /// The checks whose outcome starts a run, each once. pub(crate) expected_checks: &'static [&'static str], } @@ -119,3 +119,16 @@ pub(crate) struct SkipInFlightTestCase { pub(crate) after_skip: &'static [crate::declarations::models::TriggerChange], pub(crate) expected_next_event: &'static str, } + +/// A started tick, then one that ends as `tick`, with some phases stored as an earlier release wrote them. +pub(crate) struct UnreadableTickTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) tick: fn() -> crate::sensors::models::SensorEvaluationOutcome, + /// Which phases no longer decode; `$2` is the first tick and `$3` the second. + pub(crate) unreadable: &'static str, + /// Newest first: each tick's outcome, and whether it says it can't be read. + pub(crate) expected_ticks: [(&'static str, bool); 2], + /// `None` when not failing, else the reason shown on the page and in the trigger list. + pub(crate) expected_failing: Option>, +} diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_unreadable_ticks.rs b/crates/sqlbuild-orchestration/tests/sensors/test_unreadable_ticks.rs new file mode 100644 index 0000000000..70484319bb --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/sensors/test_unreadable_ticks.rs @@ -0,0 +1,202 @@ +//! A tick an earlier release stored in a form that no longer decodes loses only its own details. + +use chrono::{TimeDelta, Utc}; +use serde_json::json; +use uuid::Uuid; + +use crate::credentials::models::DefaultRole; +use crate::credentials::tests::role_helpers::{credentials, role_fixture}; +use crate::declarations::main::list_person_triggers::list_person_triggers; +use crate::declarations::main::list_triggers::list_triggers; +use crate::scheduler::tests::contracts::helpers::{acquire_lease, execute_with}; +use crate::sensors::constants::UNREADABLE_TICK; +use crate::sensors::main::begin_sensor_evaluation::begin_sensor_evaluation; +use crate::sensors::main::read_person_sensor::read_person_sensor; +use crate::sensors::tests::helpers::{ + append_events, complete_starting_job, completed_tick, failed_tick, record_tick, snapshot, +}; +use crate::sensors::tests::test_types::UnreadableTickTestCase; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::Parameter; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_tick_an_earlier_release_stored_unreadable_when_people_read_the_sensor_then_the_page_loads_and_that_tick_says_so() + { + let test_cases = [ + UnreadableTickTestCase { + description: "Sqlite: every phase of a failed tick", + backend: Backend::Sqlite, + tick: failed_tick, + unreadable: "evaluation_id=$3 AND $2 IS NOT NULL", + expected_ticks: [("failed", true), ("started", false)], + expected_failing: Some(Some(UNREADABLE_TICK)), + }, + UnreadableTickTestCase { + description: "Sqlite: only how the failed tick ended", + backend: Backend::Sqlite, + tick: failed_tick, + unreadable: "evaluation_id=$3 AND phase<>'requested' AND $2 IS NOT NULL", + expected_ticks: [("failed", true), ("started", false)], + expected_failing: Some(Some(UNREADABLE_TICK)), + }, + UnreadableTickTestCase { + description: "Sqlite: only the request of a failed tick", + backend: Backend::Sqlite, + tick: failed_tick, + unreadable: "evaluation_id=$3 AND phase='requested' AND $2 IS NOT NULL", + expected_ticks: [("failed", false), ("started", false)], + expected_failing: Some(None), + }, + UnreadableTickTestCase { + description: "Sqlite: a tick that started runs", + backend: Backend::Sqlite, + tick: failed_tick, + unreadable: "evaluation_id=$2 AND $3 IS NOT NULL", + expected_ticks: [("failed", false), ("started", true)], + expected_failing: Some(None), + }, + UnreadableTickTestCase { + description: "Sqlite: every tick, the newest handled", + backend: Backend::Sqlite, + tick: completed_tick, + unreadable: "evaluation_id IN ($2, $3)", + expected_ticks: [("handled", true), ("started", true)], + expected_failing: None, + }, + UnreadableTickTestCase { + description: "Postgres: every phase of a failed tick", + backend: Backend::Postgres, + tick: failed_tick, + unreadable: "evaluation_id=$3 AND $2 IS NOT NULL", + expected_ticks: [("failed", true), ("started", false)], + expected_failing: Some(Some(UNREADABLE_TICK)), + }, + UnreadableTickTestCase { + description: "Postgres: only how the failed tick ended", + backend: Backend::Postgres, + tick: failed_tick, + unreadable: "evaluation_id=$3 AND phase<>'requested' AND $2 IS NOT NULL", + expected_ticks: [("failed", true), ("started", false)], + expected_failing: Some(Some(UNREADABLE_TICK)), + }, + UnreadableTickTestCase { + description: "Postgres: only the request of a failed tick", + backend: Backend::Postgres, + tick: failed_tick, + unreadable: "evaluation_id=$3 AND phase='requested' AND $2 IS NOT NULL", + expected_ticks: [("failed", false), ("started", false)], + expected_failing: Some(None), + }, + UnreadableTickTestCase { + description: "Postgres: a tick that started runs", + backend: Backend::Postgres, + tick: failed_tick, + unreadable: "evaluation_id=$2 AND $3 IS NOT NULL", + expected_ticks: [("failed", false), ("started", true)], + expected_failing: Some(None), + }, + UnreadableTickTestCase { + description: "Postgres: every tick, the newest handled", + backend: Backend::Postgres, + tick: completed_tick, + unreadable: "evaluation_id IN ($2, $3)", + expected_ticks: [("handled", true), ("started", true)], + expected_failing: None, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let roles = role_fixture(store).await; + let location = roles.location_id; + let mut input = snapshot(location); + input.generation = 2; + publish_snapshot(store, &input).await.expect("publish"); + let trigger = list_triggers(store, location, "development") + .await + .expect("triggers") + .remove(0); + let lease = acquire_lease(store, Uuid::now_v7()) + .await + .expect("elect") + .expect("leader"); + append_events(store, 0..1, Utc::now()).await; + let first = begin_sensor_evaluation(store, &lease, (trigger.trigger_id, None)) + .await + .expect("request") + .expect("due"); + let runs = complete_starting_job(store, &lease, &first) + .await + .expect("started"); + let second = + record_tick(store, &first, TimeDelta::seconds(1), (test_case.tick)()).await; + execute_with( + store, + &format!( + "UPDATE sqb_sensor_evaluation_events SET fact_json=$1 WHERE {}", + test_case.unreadable + ), + vec![ + Parameter::Json(json!({"written_by": "an earlier release"})), + Parameter::Id(first.evaluation_id), + Parameter::Id(second.evaluation_id), + ], + ) + .await; + let who = (&roles.context, credentials(&roles.administrator)); + let state = read_person_sensor( + store, + who, + ((location, "development"), (trigger.trigger_id, 10)), + DefaultRole::None, + ) + .await + .expect("the page loads") + .expect("sensor"); + let listed = + list_person_triggers(store, who, (location, "development"), DefaultRole::None) + .await + .expect("the trigger list loads") + .remove(0); + let ticks: Vec<(&str, bool)> = state + .evaluations + .iter() + .map(|tick| (tick.outcome.as_str(), tick.unreadable.is_some())) + .collect(); + let failing = state + .failing + .as_ref() + .map(|failing| failing.reason.as_deref()); + + assert_eq!( + (ticks, failing, state.evaluations[1].run_ids.len()), + ( + test_case.expected_ticks.to_vec(), + test_case.expected_failing, + runs, + ), + "{}: only that tick loses its details", + test_case.description + ); + assert_eq!( + listed.sensor_failing, state.failing, + "{}: the list says the same", + test_case.description + ); + assert_eq!( + state.evaluations[0].event_id, + second.event.as_ref().map(|event| event.id().to_owned()), + "{}: the tick keeps its event", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs b/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs index 057eeb18a5..535e25322b 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs @@ -14,9 +14,7 @@ use crate::scheduler::tests::contracts::helpers::acquire_lease; use crate::sensors::tests::helpers::{add_old_form_sensor, finish_run, triggers_document}; use crate::sensors::tests::test_types::SensorUpgradeTestCase; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; -use crate::store::main::{ - begin::begin, commit::commit, migrate_store::migrate_store, query::query, -}; +use crate::store::main::{begin::begin, commit::commit, query::query}; use crate::store::models::TransactionMode; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store::tests::store_test_types::Backend; @@ -72,9 +70,13 @@ fn given_a_snapshot_with_an_old_form_sensor_when_the_store_upgrades_then_its_job .expect("publish before upgrade"); add_old_form_sensor(store, &snapshot).await; - migrate_store(store).await.expect("upgrade"); + migrate_with(store, &MIGRATIONS[..4]) + .await + .expect("upgrade to version 5"); let migrated = triggers_document(store, snapshot.snapshot_id).await; - migrate_store(store).await.expect("open again"); + migrate_with(store, &MIGRATIONS[..4]) + .await + .expect("open again"); let again = drop_old_form_sensors(begin(store, TransactionMode::Write).await.expect("step")) .await diff --git a/crates/sqlbuild-orchestration/tests/store/schema/helpers.rs b/crates/sqlbuild-orchestration/tests/store/schema/helpers.rs index 4013ef52f0..5c699a3c06 100644 --- a/crates/sqlbuild-orchestration/tests/store/schema/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/store/schema/helpers.rs @@ -4,6 +4,10 @@ use std::io::{BufRead, BufReader}; use std::path::Path; use std::process::{Command, Stdio}; +use crate::authorization::main::service_accounts::create_service_account::create_service_account; +use crate::credentials::models::{ + AuditContext, BuiltinRole, NewServiceAccount, ServiceAccountAuthority, +}; use crate::credentials::tests::location_helpers::create_location; use crate::store::main::begin::begin; use crate::store::main::commit::commit; @@ -11,8 +15,9 @@ use crate::store::main::migrate_store::migrate_store; use crate::store::main::open_store::open_store; use crate::store::main::query::query; use crate::store::models::{ControlStore, Parameter, TransactionMode}; +use crate::store::tests::replica_helpers::second_store; use crate::store::tests::schema::test_types::StoreDialect; -use crate::store::tests::store_helpers::run; +use crate::store::tests::store_helpers::{close_store, run}; use crate::store::tests::store_test_types::Backend; use crate::store::types::Row; use crate::store_migrations::constants::{POSTGRES_BASELINE_CHECKSUMS, SQLITE_BASELINE_CHECKSUMS}; @@ -257,9 +262,10 @@ pub(crate) async fn schema_shape(store: &ControlStore, dialect: &StoreDialect) - shape } -/// Every row of `tables`, in primary-key order. +/// Every row of `tables`, in primary-key order, on new connections: PostgreSQL refuses a `SELECT *` prepared before a column was added. pub(crate) async fn table_rows(store: &ControlStore, tables: &[&str]) -> Vec> { - let mut transaction = begin(store, TransactionMode::Read) + let reader: ControlStore = second_store(store).await; + let mut transaction = begin(&reader, TransactionMode::Read) .await .expect("begin read"); let mut all: Vec> = Vec::new(); @@ -275,6 +281,7 @@ pub(crate) async fn table_rows(store: &ControlStore, tables: &[&str]) -> Vec Vec rows.iter().map(|row| text(row, "item")).collect() } +/// The key of a service account the store's owner adds, which needs the service account tables. +pub(crate) async fn service_account_key(store: &ControlStore) -> String { + let context = AuditContext { + actor: "local-control-store-owner".into(), + granting_role: "control-store-owner".into(), + request_id: uuid::Uuid::now_v7(), + ip_address: None, + }; + let request = NewServiceAccount { + name: "orders-deploy".into(), + description: None, + role: BuiltinRole::Developer, + }; + create_service_account( + store, + (&context, ServiceAccountAuthority::Owner), + (&request, None), + ) + .await + .expect("a service account") + .key +} + /// The store's recorded schema version. pub(crate) async fn recorded_version(store: &ControlStore) -> Option { let transaction = begin(store, TransactionMode::Read) diff --git a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs index a762fb5b9a..fd58087e69 100644 --- a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs +++ b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs @@ -1,16 +1,18 @@ //! Numbered control-store migrations: baseline upgrades, table rebuilds, refusals and the dry run. +use crate::credentials::main::service_keys::authenticate_service_key::authenticate_service_key; +use crate::credentials::models::ServiceKeyCheck; use crate::store::constants::{INDEXES, SCHEMA}; use crate::store::main::migrate_store::migrate_store; use crate::store::tests::schema::helpers::{ BASELINE_ROWS, POPULATED_TABLES, POSTGRES_STORE, SQLITE_STORE, create_unversioned_baseline, execute, migration_names, query_items, rebuilt_runs_table, recorded_version, schema_shape, - table_rows, without_added_columns, + service_account_key, table_rows, without_added_columns, }; use crate::store::tests::schema::test_types::{ BaselineUpgradeTestCase, BrokenMigrationTestCase, LiveWorkUpgradeTestCase, - MigrationRefusalTestCase, PinnedChecksumTestCase, StoreMigrationPlanTestCase, - TableRebuildTestCase, + MigrationRefusalTestCase, PinnedChecksumTestCase, ServiceAccountUpgradeTestCase, + StoreMigrationPlanTestCase, TableRebuildTestCase, }; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store_migrations::_helpers::migration::{ @@ -50,6 +52,22 @@ const SQLITE_CHECKSUMS: &[(i64, &str)] = &[ 5, "48d191962e39b22a3b95b9495da6371067a3fd3cfc51192bcfe0ac0192edcba2", ), + ( + 6, + "efeb5ed2f8bd2d191ec6848427c47201892b299d92c92ca7d0fcdacd0a49d69e", + ), + ( + 7, + "56f505ab32cf6ce3e694461516616d390c008ff5622af56001c3443028b230d4", + ), + ( + 8, + "caad867ae87f86bedb52d51330f390aba223630f147b86353f899a189160e245", + ), + ( + 9, + "53e0dbe5dd3eb23174e46480e8c805d9ede865a65f132c545f989603f0a93695", + ), ]; const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ ( @@ -73,6 +91,22 @@ const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ 5, "5a86ec47fce6ba3ced0badeb7ddb5b54d5bd2408fbe917b5c11391d362387ebb", ), + ( + 6, + "b6400df03f6b2bf630f7a26b4f1f070fd12dfe5097fe471cb175a65b002a0c08", + ), + ( + 7, + "3279facbd626157c799e4ceea29d61572b1f3af2ece51281e55b79dfc612e1e5", + ), + ( + 8, + "716de0aa5611c1a57238550853888daa3e84cd10b7d1a00297766e17b876b938", + ), + ( + 9, + "36e079cd622544e221ddfb9bc8837d8030586f7628aaa77da3c1763abb4c4442", + ), ]; /// A version 1 store mid-run: a child run holding a concurrency slot, a jobs document and an audit result. const VERSION_1_LIVE_WORK: &str = "ALTER TABLE sqb_schema_version ADD COLUMN version BIGINT; \ @@ -189,6 +223,100 @@ fn given_store_at_the_baseline_when_migrating_then_it_matches_a_new_store_and_ke } } +#[test] +fn given_a_store_from_before_service_accounts_when_upgraded_then_it_matches_a_new_store_and_takes_keys() + { + let test_cases = [ + ServiceAccountUpgradeTestCase { + description: "SQLite store from the version before service accounts", + dialect: &SQLITE_STORE, + versions_behind: 0, + expected_objects_before: 0, + expected_version: current_version(MIGRATIONS), + }, + ServiceAccountUpgradeTestCase { + description: "PostgreSQL store from the version before service accounts", + dialect: &POSTGRES_STORE, + versions_behind: 0, + expected_objects_before: 0, + expected_version: current_version(MIGRATIONS), + }, + ServiceAccountUpgradeTestCase { + description: "SQLite store from two versions earlier", + dialect: &SQLITE_STORE, + versions_behind: 2, + expected_objects_before: 0, + expected_version: current_version(MIGRATIONS), + }, + ServiceAccountUpgradeTestCase { + description: "PostgreSQL store from two versions earlier", + dialect: &POSTGRES_STORE, + versions_behind: 2, + expected_objects_before: 0, + expected_version: current_version(MIGRATIONS), + }, + ]; + for test_case in test_cases { + run(async { + let backend = test_case.dialect.backend; + let upgraded = open_test_store(backend).await.expect("required backend"); + let created = open_test_store(backend).await.expect("required backend"); + let store = &upgraded.store; + create_unversioned_baseline( + store, + test_case.dialect, + test_case.dialect.baseline_checksum, + ) + .await; + let position = MIGRATIONS + .iter() + .position(|migration| migration.name == "service_accounts") + .expect("the service accounts migration"); + migrate_with(store, &MIGRATIONS[..position - test_case.versions_behind]) + .await + .expect("a store from an older release"); + let objects_before = schema_shape(store, test_case.dialect) + .await + .into_iter() + .filter(|item| item.contains("service_account")) + .count(); + let before = table_rows(store, &POPULATED_TABLES).await; + + migrate_store(store).await.expect("upgrade the older store"); + let kept = without_added_columns(table_rows(store, &POPULATED_TABLES).await, &before); + let key = service_account_key(store).await; + migrate_store(store) + .await + .expect("open the upgraded store again"); + migrate_store(&created.store).await.expect("create a store"); + let check = authenticate_service_key(store, &key, chrono::Utc::now()) + .await + .expect("check the key"); + + assert_eq!( + ( + objects_before, + schema_shape(store, test_case.dialect).await, + kept, + recorded_version(store).await, + matches!(check, ServiceKeyCheck::Accepted(_)), + ), + ( + test_case.expected_objects_before, + schema_shape(&created.store, test_case.dialect).await, + before, + Some(test_case.expected_version), + true, + ), + "{}: the migration adds what a new store has, keeps every row and takes keys", + test_case.description + ); + close_test_store(upgraded).await; + close_test_store(created).await; + }); + } +} + #[test] fn given_a_version_1_store_with_live_work_when_migrating_then_rows_default_and_references_join() { let test_cases = [ diff --git a/crates/sqlbuild-orchestration/tests/store/schema/test_types.rs b/crates/sqlbuild-orchestration/tests/store/schema/test_types.rs index 3b665ec975..791609d30c 100644 --- a/crates/sqlbuild-orchestration/tests/store/schema/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/store/schema/test_types.rs @@ -98,3 +98,14 @@ pub(crate) struct BrokenMigrationTestCase { pub(crate) expected_fragment: &'static str, pub(crate) expected_version: Option, } + +/// A store from before the service accounts migration, built from the frozen baseline by the real migrations. +pub(crate) struct ServiceAccountUpgradeTestCase { + pub(crate) description: &'static str, + pub(crate) dialect: &'static StoreDialect, + /// How many versions older than the one just before service accounts the store is. + pub(crate) versions_behind: usize, + /// Schema objects naming service accounts in the older store. + pub(crate) expected_objects_before: usize, + pub(crate) expected_version: i64, +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/adapter_connects.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/adapter_connects.rs new file mode 100644 index 0000000000..c451813b15 --- /dev/null +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/adapter_connects.rs @@ -0,0 +1,37 @@ +//! The adapter connects in progress, found on the running threads' stacks. + +use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult, Python}; + +use crate::boundary::main::imported::imported; +use crate::native_host::constants::{ADAPTER_BASE_CLASS, ADAPTER_BASE_MODULE, CONNECT_METHOD}; + +/// Each running frame of an adapter's `connect`; none before the adapters are imported. +pub(crate) fn connects_in_progress(py: Python<'_>) -> PyResult>> { + let modules: Bound<'_, PyAny> = py.import("sys")?.getattr("modules")?; + let module: Bound<'_, PyAny> = modules.call_method1("get", (ADAPTER_BASE_MODULE,))?; + let Some(adapter) = module.getattr_opt(ADAPTER_BASE_CLASS)? else { + return Ok(Vec::new()); + }; + let stacks: Bound<'_, PyAny> = imported(py, "sys", "_current_frames")? + .call0()? + .call_method0("values")?; + let mut connecting: Vec> = Vec::new(); + for top in stacks.try_iter()? { + let mut frame: Bound<'_, PyAny> = top?; + while !frame.is_none() { + if frame + .getattr("f_code")? + .getattr("co_name")? + .eq(CONNECT_METHOD)? + { + let receiver: Bound<'_, PyAny> = + frame.getattr("f_locals")?.call_method1("get", ("self",))?; + if receiver.is_instance(&adapter)? { + connecting.push(frame.clone().unbind()); + } + } + frame = frame.getattr("f_back")?; + } + } + Ok(connecting) +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/forced_exit.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/forced_exit.rs new file mode 100644 index 0000000000..504e17600e --- /dev/null +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/forced_exit.rs @@ -0,0 +1,63 @@ +//! Ending an interrupted process without waiting for what is left in it. + +use std::io::{IsTerminal, Write}; +use std::sync::atomic::Ordering; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; +use pyo3::types::{PyDict, PyDictMethods}; +use sqlbuild_host::entries::models::ExecutorHost; + +use crate::boundary::main::imported::imported; +use crate::native_host::_helpers::terminal_settings::restore_terminal; +use crate::native_host::constants::{FORCED_EXIT_WAIT, INTERRUPTED_CODE, INTERRUPTED_LINE}; +use crate::native_host::main::host_entry::host_entry; +use crate::native_host::models::InterruptWatch; + +/// Start `target` on a Python daemon thread, which interpreter exit doesn't wait for. +fn background<'py>(target: Bound<'py, PyAny>) -> PyResult> { + let py: Python<'py> = target.py(); + let options: Bound<'py, PyDict> = PyDict::new(py); + options.set_item("target", target)?; + options.set_item("daemon", true)?; + let thread: Bound<'py, PyAny> = + imported(py, "threading", "Thread")?.call((), Some(&options))?; + thread.call_method0("start")?; + Ok(thread) +} + +/// Cancel every running statement without waiting for the warehouse's answer. +pub(crate) fn cancel_statements(py: Python<'_>) -> PyResult> { + background(host_entry(py, ExecutorHost::CancelRunningStatements)?) +} + +/// The one line an interrupted command ends with. +pub(crate) fn announce(watch: &InterruptWatch) { + if watch.announced.swap(true, Ordering::SeqCst) { + return; + } + let mut stderr: std::io::Stderr = std::io::stderr(); + let lead: &str = if stderr.is_terminal() { "\n" } else { "" }; + drop(writeln!(stderr, "{lead}{INTERRUPTED_LINE}")); +} + +/// Cancel statements, flush, restore the terminal, say so and end the process with 130. +pub(crate) fn force_exit(py: Python<'_>, watch: &InterruptWatch) -> PyResult<()> { + let wait = |thread: PyResult>| { + drop( + thread + .and_then(|thread| thread.call_method1("join", (FORCED_EXIT_WAIT.as_secs_f64(),))), + ); + }; + wait(cancel_statements(py)); + wait( + imported(py, "sys", "stdout") + .and_then(|stdout| stdout.getattr("flush")) + .and_then(background), + ); + if let Some(terminal) = &watch.terminal { + drop(restore_terminal(py, terminal)); + } + announce(watch); + imported(py, "os", "_exit")?.call1((INTERRUPTED_CODE,))?; + Ok(()) +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/interrupt.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/interrupt.rs index e2b6d9e56d..869a876a80 100644 --- a/crates/sqlbuild-python-base/src/native_host/_helpers/interrupt.rs +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/interrupt.rs @@ -1,14 +1,22 @@ //! Python's default compilation Ctrl+C handler, retained across unraisable callbacks. use std::cell::Cell; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; use pyo3::exceptions::PyKeyboardInterrupt; use pyo3::prelude::{Py, PyAny, PyAnyMethods, PyModule, PyResult, Python}; +use crate::native_host::models::InterruptWatch; + thread_local! { pub(crate) static INTERRUPTED: Cell = const { Cell::new(false) }; } pub(crate) const SIGINT: i64 = 2; +/// Whether Ctrl+C reached the `sqb` process's watch, which sees it before any handler runs. +pub(crate) static WATCHED_INTERRUPT: AtomicBool = AtomicBool::new(false); +/// The watch of the running command, which a command's end asks to catch up. +pub(crate) static ACTIVE_WATCH: Mutex>> = Mutex::new(None); /// Whether the default handler observed Ctrl+C during the current command. pub(crate) fn interrupted() -> bool { @@ -39,3 +47,8 @@ pub(crate) fn restore_signal_handler( } Ok(()) } + +/// Whether the default handler or the process's watch observed Ctrl+C during the current command. +pub(crate) fn interrupt_observed() -> bool { + interrupted() || WATCHED_INTERRUPT.load(Ordering::SeqCst) +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/mod.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/mod.rs index adf517e70e..819b334425 100644 --- a/crates/sqlbuild-python-base/src/native_host/_helpers/mod.rs +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/mod.rs @@ -6,4 +6,13 @@ pub(crate) mod interrupt; pub(crate) mod results; +pub(crate) mod adapter_connects; pub(crate) mod dialect; + +pub(crate) mod forced_exit; + +pub(crate) mod signal_watcher; + +pub(crate) mod terminal_settings; + +pub(crate) mod watch_session; diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs index f6662f4c46..518d3d3203 100644 --- a/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs @@ -13,7 +13,7 @@ use sqlbuild_host::models::{ AuditOutcome, AuditRunScope, AuditSeverity, BuildExecutionResult, BuildExecutionTimings, BuildStatus, CancellationOutcome, ExecutionPhase, ExecutionResourceKind, ExecutionStatus, FunctionExecutionResult, HookExecutionResult, HookPhase, ItemKind, ItemTimeoutReport, - LifeCycleEvent, LifeCycleEventKind, LoadExecutionResult, MeasuredValue, + LifeCycleEvent, LifeCycleEventKind, LoadExecutionResult, LogLevel, MeasuredValue, MicrobatchAccountingInterval, MicrobatchLimitAction, ModelExecutionResult, ScenarioAssertionExpectationExecutionResult, ScenarioExpectedExpectationExecutionResult, ScenarioLocalRunStatus, ScenarioRunResult, SeedExecutionResult, SkipMode, @@ -101,6 +101,7 @@ enums!( AttachedAuditTargetKind, AuditEvaluationMode, LifeCycleEventKind, + LogLevel, AuditAttachmentKind, AuditSeverity, AuditOutcome, @@ -135,7 +136,11 @@ record!(BuildExecutionTimings { schema_preparation_seconds, execution_seconds, }); -record!(LifeCycleEvent { kind, content }); +record!(LifeCycleEvent { + kind, + content, + level +}); record!(HookExecutionResult { phase, index, @@ -157,7 +162,8 @@ record!(MicrobatchAccountingInterval { }); record!(ModelExecutionResult { model_name, status, failed_phase, staging_relation, promoted_relation, duration_ms, - batch_count, batch_size, rows_affected, cursor_range_start, cursor_range_end, cursor_type, + batch_count, batch_size, rows_affected, table_rows, cursor_range_start, cursor_range_end, + cursor_type, cursor_grain, empty_cursor_inputs, waiting_on_empty_inputs, future_cursor_safety, maximum_start_safety, audit_results, warning_messages, lifecycle_events, hook_results, skip_mode, skip_reason, error_code, error_help, error_message, failed_sql, @@ -352,6 +358,7 @@ impl<'py> ReadResult<'py> for LoadExecutionResult> { resource_kind: ReadResult::read(&field(value, "resource_kind")?)?, staging_relation: ReadResult::read(&field(value, "staging_relation")?)?, rows_loaded: ReadResult::read(&field(value, "rows_loaded")?)?, + rows_affected: ReadResult::read(&field(value, "rows_affected")?)?, duration_ms: ReadResult::read(&field(value, "duration_ms")?)?, lifecycle_events: ReadResult::read(&field(value, "lifecycle_events")?)?, skip_mode: ReadResult::read(&field(value, "skip_mode")?)?, diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/signal_watcher.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/signal_watcher.rs new file mode 100644 index 0000000000..56e7606b7c --- /dev/null +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/signal_watcher.rs @@ -0,0 +1,208 @@ +//! The thread that follows SIGINT while a command runs, leaving Python's handlers as they are, and the socket pair it reads without the interpreter. + +use std::io::{ErrorKind, Read, Write}; +use std::sync::atomic::Ordering; +use std::time::{Duration, Instant}; + +use pyo3::prelude::{Py, PyAny, PyAnyMethods, PyResult, Python}; +use sqlbuild_host::entries::models::ExecutorHost; + +use crate::boundary::main::imported::imported; +use crate::native_host::_helpers::adapter_connects::connects_in_progress; +use crate::native_host::_helpers::forced_exit::{cancel_statements, force_exit}; +use crate::native_host::_helpers::interrupt::WATCHED_INTERRUPT; +use crate::native_host::constants::{ + GRACE, INTERRUPT_BYTE, POLL, RECEIVE_BYTES, STEP_THREAD_PREFIX, STOP_BYTE, SYNC_BYTE, +}; +use crate::native_host::main::host_entry::host_entry; +use crate::native_host::models::{InterruptPresses, InterruptWatch}; +use crate::native_host::types::WakeupSocket; + +/// Whether a statement has ever run, and whether one runs now. +fn statement_activity(py: Python<'_>) -> PyResult<(bool, bool)> { + host_entry(py, ExecutorHost::StatementActivity)? + .call0()? + .extract() +} + +/// Read the wakeup descriptor until told to stop, forcing the exit where `may_force` allows. A press is noted as soon as it is read, before the interpreter is taken back, so a command that returns meanwhile still ends as interrupted. +pub(crate) fn watch_signals(py: Python<'_>, watch: &InterruptWatch) -> PyResult<()> { + let mut presses: Option = None; + loop { + let wait: Option = presses.as_ref().map(|_| POLL); + let received: Vec = py.detach(|| { + let received = receive(&watch.receiver, wait); + if received + .as_ref() + .is_ok_and(|bytes| bytes.contains(&INTERRUPT_BYTE)) + && !(watch.terminated)() + { + WATCHED_INTERRUPT.store(true, Ordering::SeqCst); + } + if let Ok(bytes) = &received { + acknowledge_syncs(watch, bytes); + } + received + })?; + let count: usize = received + .iter() + .filter(|byte| **byte == INTERRUPT_BYTE) + .count(); + let terminating: bool = (watch.terminated)(); + if count > 0 && !terminating { + WATCHED_INTERRUPT.store(true, Ordering::SeqCst); + presses = Some(pressed(py, presses, count)); + watch.pressed.store(true, Ordering::SeqCst); + } + if received.contains(&STOP_BYTE) { + return Ok(()); + } + if let Some(presses) = &presses + && !terminating + && presses.last.elapsed() >= GRACE + && may_force(py, presses) + { + force_exit(py, watch)?; + } + } +} + +/// Count presses; the first notes discovered steps and the connects in progress, and cancels the statements running then, as SIGTERM does, so a driver waiting in native code returns. +fn pressed(py: Python<'_>, presses: Option, count: usize) -> InterruptPresses { + let last: Instant = Instant::now(); + if let Some(presses) = presses { + return InterruptPresses { + count: presses.count + count, + last, + connecting: presses.connecting, + stepping: presses.stepping, + }; + } + let stepping: bool = steps_have_threads(py).unwrap_or_default(); + let connecting = connects_in_progress(py).unwrap_or_default(); + if statement_activity(py).is_ok_and(|(_, running)| running) { + drop(cancel_statements(py)); + } + InterruptPresses { + count, + last, + connecting, + stepping, + } +} + +/// Whether ending the process cuts no cleanup short, or was asked for twice: the connect waiting at the press still waits, or no statement has ever run. One press never forces it once discovered steps had threads: their pool reports them within its own grace, and the command then records and exits. +fn may_force(py: Python<'_>, presses: &InterruptPresses) -> bool { + if presses.count > 1 { + return true; + } + if presses.stepping { + return false; + } + if !presses.connecting.is_empty() { + let current = connects_in_progress(py).unwrap_or_default(); + for frame in &presses.connecting { + if is_running(frame, ¤t) { + return true; + } + } + } + statement_activity(py).is_ok_and(|(ever, _)| !ever) +} + +fn is_running(frame: &Py, running: &[Py]) -> bool { + running.iter().any(|current| current.is(frame)) +} + +/// Whether a pool of discovered steps has threads, found by their name; it keeps them until it has settled its steps. +fn steps_have_threads(py: Python<'_>) -> PyResult { + for thread in imported(py, "threading", "enumerate")? + .call0()? + .try_iter()? + { + let name: String = thread?.getattr("name")?.extract()?; + if name.starts_with(STEP_THREAD_PREFIX) { + return Ok(true); + } + } + Ok(false) +} + +/// A connected pair: the end the watcher reads, and the non-blocking end Python's wakeup descriptor writes. +#[cfg(unix)] +pub(crate) fn wakeup_pair() -> std::io::Result<(WakeupSocket, WakeupSocket)> { + let (receiver, sender) = std::os::unix::net::UnixStream::pair()?; + sender.set_nonblocking(true)?; + Ok((receiver, sender)) +} + +/// A connected pair over loopback, as Python's `socket.socketpair` makes one on Windows. +#[cfg(windows)] +pub(crate) fn wakeup_pair() -> std::io::Result<(WakeupSocket, WakeupSocket)> { + let listener = std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?; + let sender = std::net::TcpStream::connect(listener.local_addr()?)?; + let (receiver, peer) = listener.accept()?; + if peer != sender.local_addr()? { + return Err(std::io::Error::other( + "an unexpected connection to the wakeup socket", + )); + } + sender.set_nonblocking(true)?; + Ok((receiver, sender)) +} + +/// The descriptor `signal.set_wakeup_fd` takes for `sender`. +#[cfg(unix)] +pub(crate) fn wakeup_descriptor(sender: &WakeupSocket) -> i64 { + i64::from(std::os::fd::AsRawFd::as_raw_fd(sender)) +} + +/// The socket handle `signal.set_wakeup_fd` takes for `sender`. +#[cfg(windows)] +pub(crate) fn wakeup_descriptor(sender: &WakeupSocket) -> i64 { + i64::try_from(std::os::windows::io::AsRawSocket::as_raw_socket(sender)).unwrap_or(-1) +} + +/// The bytes that arrived within `wait`, or until some arrive when `wait` is `None`; a closed sender reads as the stop byte. +pub(crate) fn receive(receiver: &WakeupSocket, wait: Option) -> std::io::Result> { + receiver.set_read_timeout(wait)?; + let mut bytes: [u8; RECEIVE_BYTES] = [0; RECEIVE_BYTES]; + let mut reader: &WakeupSocket = receiver; + match reader.read(&mut bytes) { + Ok(0) => Ok(vec![STOP_BYTE]), + Ok(read) => Ok(bytes[..read].to_vec()), + Err(error) + if matches!( + error.kind(), + ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted + ) => + { + Ok(Vec::new()) + } + Err(error) => Err(error), + } +} + +/// Count the sync bytes just read and wake the command's end waiting on them. +fn acknowledge_syncs(watch: &InterruptWatch, bytes: &[u8]) { + let read: u64 = bytes.iter().filter(|byte| **byte == SYNC_BYTE).count() as u64; + if read > 0 { + *watch + .syncs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) += read; + watch.synced.notify_all(); + } +} + +/// Ask the watcher to confirm it has read everything written before this. +pub(crate) fn send_sync(sender: &WakeupSocket) -> std::io::Result<()> { + let mut writer: &WakeupSocket = sender; + writer.write_all(&[SYNC_BYTE]) +} + +/// Tell the watcher to stop. +pub(crate) fn send_stop(sender: &WakeupSocket) -> std::io::Result<()> { + let mut writer: &WakeupSocket = sender; + writer.write_all(&[STOP_BYTE]) +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/terminal_settings.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/terminal_settings.rs new file mode 100644 index 0000000000..9b15194b37 --- /dev/null +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/terminal_settings.rs @@ -0,0 +1,31 @@ +//! The terminal's settings, which a forced exit puts back after a hidden-input prompt. + +use pyo3::prelude::{Py, PyAny, PyAnyMethods, PyResult, Python}; + +use crate::boundary::main::imported::imported; + +/// The first standard descriptor that is a terminal, with its settings; `None` without one. +pub(crate) fn terminal_settings(py: Python<'_>) -> Option<(i32, Py)> { + for descriptor in [0, 2, 1] { + let settings: PyResult> = imported(py, "termios", "tcgetattr") + .and_then(|read| read.call1((descriptor,))) + .map(pyo3::Bound::unbind); + if let Ok(settings) = settings { + return Some((descriptor, settings)); + } + } + None +} + +/// Put `settings` back at once. +pub(crate) fn restore_terminal( + py: Python<'_>, + (descriptor, settings): &(i32, Py), +) -> PyResult<()> { + let termios = py.import("termios")?; + termios.call_method1( + "tcsetattr", + (*descriptor, termios.getattr("TCSANOW")?, settings.bind(py)), + )?; + Ok(()) +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/watch_session.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/watch_session.rs new file mode 100644 index 0000000000..7f4e4979ca --- /dev/null +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/watch_session.rs @@ -0,0 +1,148 @@ +//! One watched command: the watch started before it and settled after it. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; + +use pyo3::exceptions::{PyKeyboardInterrupt, PyRuntimeError}; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; + +use crate::boundary::main::imported::imported; +use crate::native_host::_helpers::forced_exit::{announce, force_exit}; +use crate::native_host::_helpers::interrupt::{ACTIVE_WATCH, WATCHED_INTERRUPT}; +use crate::native_host::_helpers::signal_watcher::{ + send_stop, send_sync, wakeup_descriptor, wakeup_pair, watch_signals, +}; +use crate::native_host::_helpers::terminal_settings::terminal_settings; +use crate::native_host::constants::{GRACE, INTERRUPTED_CODE, POLL, SYNC_WAIT, TERMINATED_CODE}; +use crate::native_host::models::{InterruptSession, InterruptWatch}; + +/// Start watching; `None` leaves an ignored or embedder's SIGINT handler alone. +pub(crate) fn start_watching( + py: Python<'_>, + terminated: fn() -> bool, +) -> PyResult> { + let signal = py.import("signal")?; + let default: Bound<'_, PyAny> = signal.getattr("default_int_handler")?; + let handler = signal.call_method1("getsignal", (signal.getattr("SIGINT")?,))?; + if !handler.is(&default) { + return Ok(None); + } + let (receiver, sender) = wakeup_pair()?; + let watch: Arc = Arc::new(InterruptWatch { + receiver, + sender, + syncs: std::sync::Mutex::new(0), + synced: std::sync::Condvar::new(), + terminal: terminal_settings(py), + terminated, + pressed: AtomicBool::new(false), + announced: AtomicBool::new(false), + }); + let previous = signal.call_method1("set_wakeup_fd", (wakeup_descriptor(&watch.sender),))?; + WATCHED_INTERRUPT.store(false, Ordering::SeqCst); + *active_watch() = Some(Arc::clone(&watch)); + let watched: Arc = Arc::clone(&watch); + let watcher = std::thread::Builder::new() + .name("sqlbuild-interrupt".to_owned()) + .spawn(move || Python::attach(|py| watch_signals(py, &watched)))?; + Ok(Some(InterruptSession { + watch, + watcher, + previous_wakeup: previous.unbind(), + })) +} + +/// Stop watching and give the command's exit code, or 130 when Ctrl+C stopped it. +pub(crate) fn settle( + py: Python<'_>, + session: InterruptSession, + ran: PyResult, +) -> PyResult { + let signal = py.import("signal")?; + let sigint: Bound<'_, PyAny> = signal.getattr("SIGINT")?; + let ignore = || signal.call_method1("signal", (&sigint, signal.getattr("SIG_IGN")?)); + let late: bool = ignore().is_err(); + if late { + drop(ignore()); + } + signal.call_method1("set_wakeup_fd", (session.previous_wakeup.bind(py),))?; + *active_watch() = None; + send_stop(&session.watch.sender)?; + let watcher = session.watcher; + match py.detach(|| watcher.join()) { + Ok(watched) => watched?, + Err(_panicked) => return Err(PyRuntimeError::new_err("the interrupt watcher panicked")), + } + let terminated: bool = ran.as_ref().is_ok_and(|code| *code == TERMINATED_CODE); + let raised: bool = ran + .as_ref() + .is_err_and(|error| error.is_instance_of::(py)); + if terminated || !(raised || late || session.watch.pressed.load(Ordering::SeqCst)) { + signal.call_method1("signal", (&sigint, signal.getattr("default_int_handler")?))?; + return ran; + } + end_interrupted(py, &session.watch) +} + +/// Say so, give threads left running the grace period, then give 130 or exit past them. +fn end_interrupted(py: Python<'_>, watch: &InterruptWatch) -> PyResult { + announce(watch); + let deadline: Instant = Instant::now() + GRACE; + while threads_left_running(py)? { + if Instant::now() >= deadline { + force_exit(py, watch)?; + } + py.detach(|| std::thread::sleep(POLL)); + } + Ok(INTERRUPTED_CODE) +} + +/// Whether a thread interpreter exit would wait for still has a frame; `is_alive` can't say, as an interrupted `join` marks a running thread stopped. +fn threads_left_running(py: Python<'_>) -> PyResult { + let running: Bound<'_, PyAny> = imported(py, "sys", "_current_frames")?.call0()?; + let threading = py.import("threading")?; + let current: Bound<'_, PyAny> = threading.call_method0("current_thread")?; + for thread in threading.call_method0("enumerate")?.try_iter()? { + let thread: Bound<'_, PyAny> = thread?; + if !thread.is(¤t) + && !thread.getattr("daemon")?.is_truthy()? + && running.contains(thread.getattr("ident")?)? + { + return Ok(true); + } + } + Ok(false) +} + +fn active_watch() -> std::sync::MutexGuard<'static, Option>> { + ACTIVE_WATCH + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Wait, without the interpreter, until the running command's watch has read every byte written before now, so a press already delivered counts however busy the machine is. A full socket means the watcher is behind already, and is not waited for. +pub(crate) fn catch_up(py: Python<'_>) -> PyResult<()> { + let Some(watch) = active_watch().clone() else { + return Ok(()); + }; + py.detach(|| { + let syncs = watch + .syncs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let before: u64 = *syncs; + match send_sync(&watch.sender) { + Ok(()) => { + drop( + watch + .synced + .wait_timeout_while(syncs, SYNC_WAIT, |read| *read == before), + ); + Ok(()) + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Ok(()), + Err(error) => Err(error.into()), + } + }) +} diff --git a/crates/sqlbuild-python-base/src/native_host/constants.rs b/crates/sqlbuild-python-base/src/native_host/constants.rs index ead86ed7df..a62c2b7b5a 100644 --- a/crates/sqlbuild-python-base/src/native_host/constants.rs +++ b/crates/sqlbuild-python-base/src/native_host/constants.rs @@ -1,5 +1,7 @@ //! Public constants of native host. +use std::time::Duration; + /// The calendar's evaluation window is supplied by the host, not a provider. pub const CALENDAR_WINDOW_PARAMETER: &str = "window"; @@ -29,3 +31,29 @@ pub const HISTORY_STREAM_PAGES: usize = 50; pub const ALIAS_PREFIX_TARGET: &str = "alias"; pub const ALL_PREFIX_TARGET: &str = "all"; + +/// SIGINT's number, as the wakeup descriptor carries it. +pub(crate) const INTERRUPT_BYTE: u8 = 2; +/// What stops the watcher; no signal has this number. +pub(crate) const STOP_BYTE: u8 = 0; +/// Asks the watcher to confirm it has read every byte written before it; no signal has this number. +pub(crate) const SYNC_BYTE: u8 = 255; +/// How long a command's end waits for that confirmation before it trusts what the watcher has seen. +pub(crate) const SYNC_WAIT: Duration = Duration::from_millis(200); +/// The most bytes one read of the wakeup descriptor takes. +pub(crate) const RECEIVE_BYTES: usize = 64; +/// 128 plus SIGINT, as shells report Ctrl+C. +pub(crate) const INTERRUPTED_CODE: i64 = 130; +/// 128 plus SIGTERM, which a command reports itself. +pub(crate) const TERMINATED_CODE: i64 = 143; +pub(crate) const INTERRUPTED_LINE: &str = "error: interrupted (Ctrl+C)"; +/// How long an interrupted command may take to unwind before an exit that cuts nothing short. +pub(crate) const GRACE: Duration = Duration::from_millis(600); +pub(crate) const POLL: Duration = Duration::from_millis(50); +/// How long a forced exit waits for statements to cancel, and for output to flush. +pub(crate) const FORCED_EXIT_WAIT: Duration = Duration::from_secs(1); +pub(crate) const ADAPTER_BASE_MODULE: &str = "sqlbuild.adapter.contract.classes.base_adapter"; +pub(crate) const ADAPTER_BASE_CLASS: &str = "BaseAdapter"; +pub(crate) const CONNECT_METHOD: &str = "connect"; +/// `ABANDONABLE_THREAD_PREFIX` of the discovered item pool, which names its threads with it. +pub(crate) const STEP_THREAD_PREFIX: &str = "sqlbuild-item"; diff --git a/crates/sqlbuild-python-base/src/native_host/main/interrupted.rs b/crates/sqlbuild-python-base/src/native_host/main/interrupted.rs index b626745df4..c4d25dc38f 100644 --- a/crates/sqlbuild-python-base/src/native_host/main/interrupted.rs +++ b/crates/sqlbuild-python-base/src/native_host/main/interrupted.rs @@ -1,9 +1,17 @@ -//! Whether the default handler observed Ctrl+C during the current command. +//! Whether Ctrl+C reached the current command, once the watch has read every signal delivered so far. + +use pyo3::prelude::Python; use crate::native_host::_helpers::interrupt; +use crate::native_host::_helpers::watch_session::catch_up; -/// Whether the default handler observed Ctrl+C during the current command. -#[inline] -pub fn interrupted() -> bool { - interrupt::interrupted() +/// Whether the default handler or the watch observed Ctrl+C during the current command. Until either has, the watch is asked to catch up first; a watch that can't be asked is reported as unraisable, and what it has seen so far decides. +pub fn interrupted(py: Python<'_>) -> bool { + if interrupt::interrupt_observed() { + return true; + } + if let Err(error) = catch_up(py) { + error.write_unraisable(py, None); + } + interrupt::interrupt_observed() } diff --git a/crates/sqlbuild-python-base/src/native_host/main/mod.rs b/crates/sqlbuild-python-base/src/native_host/main/mod.rs index b30fd0da60..60fcff06ba 100644 --- a/crates/sqlbuild-python-base/src/native_host/main/mod.rs +++ b/crates/sqlbuild-python-base/src/native_host/main/mod.rs @@ -9,5 +9,6 @@ pub mod log_warning_message; pub mod module_installed; pub mod python_executable; pub mod redirect_stdout_to_stderr; +pub mod run_interruptible; pub mod within_identity_pass; pub mod write_console; diff --git a/crates/sqlbuild-python-base/src/native_host/main/run_interruptible.rs b/crates/sqlbuild-python-base/src/native_host/main/run_interruptible.rs new file mode 100644 index 0000000000..b89332cf06 --- /dev/null +++ b/crates/sqlbuild-python-base/src/native_host/main/run_interruptible.rs @@ -0,0 +1,15 @@ +//! `run_interruptible`: one command in the `sqb` process, which Ctrl+C always stops. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; + +use crate::native_host::_helpers::watch_session::{settle, start_watching}; + +/// Call `run` and return its exit code, or 130 once Ctrl+C stopped it. +pub fn run_interruptible(run: &Bound<'_, PyAny>, terminated: fn() -> bool) -> PyResult { + let py: Python<'_> = run.py(); + let Some(session) = start_watching(py, terminated)? else { + return run.call0()?.extract(); + }; + let ran: PyResult = run.call0().and_then(|code| code.extract()); + settle(py, session, ran) +} diff --git a/crates/sqlbuild-python-base/src/native_host/models.rs b/crates/sqlbuild-python-base/src/native_host/models.rs index 8ce45cb900..29441efc5c 100644 --- a/crates/sqlbuild-python-base/src/native_host/models.rs +++ b/crates/sqlbuild-python-base/src/native_host/models.rs @@ -5,6 +5,7 @@ use crate::native_host::_helpers::interrupt::INTERRUPTED; use crate::native_host::_helpers::interrupt::SIGINT; use crate::native_host::_helpers::interrupt::restore_signal_handler; use crate::native_host::types::Syntax; +use crate::native_host::types::WakeupSocket; use pyo3::exceptions::PyAttributeError; use pyo3::exceptions::PyKeyboardInterrupt; use pyo3::prelude::Bound; @@ -267,3 +268,40 @@ impl Dialect { self.attribute(py, name) } } + +/// One command's watch for Ctrl+C. +#[derive(Debug)] +pub(crate) struct InterruptWatch { + /// The end of the socket pair Python's wakeup descriptor feeds. + pub(crate) receiver: WakeupSocket, + /// The end Python's wakeup descriptor writes to. + pub(crate) sender: WakeupSocket, + /// The sync bytes the watcher has read, and the signal it gives when it reads one. + pub(crate) syncs: std::sync::Mutex, + pub(crate) synced: std::sync::Condvar, + /// The terminal's descriptor and the settings it had when the command started. + pub(crate) terminal: Option<(i32, Py)>, + /// Whether SIGTERM is stopping the command, which then ends as a termination. + pub(crate) terminated: fn() -> bool, + pub(crate) pressed: std::sync::atomic::AtomicBool, + pub(crate) announced: std::sync::atomic::AtomicBool, +} + +/// The Ctrl+C presses so far. +#[derive(Debug)] +pub(crate) struct InterruptPresses { + pub(crate) count: usize, + pub(crate) last: std::time::Instant, + /// The adapter connects in progress at the first press. + pub(crate) connecting: Vec>, + /// Whether discovered steps had threads at the first press, so their pool ends the command. + pub(crate) stepping: bool, +} + +/// A watch while its command runs. +#[derive(Debug)] +pub(crate) struct InterruptSession { + pub(crate) watch: std::sync::Arc, + pub(crate) watcher: std::thread::JoinHandle>, + pub(crate) previous_wakeup: Py, +} diff --git a/crates/sqlbuild-python-base/src/native_host/types.rs b/crates/sqlbuild-python-base/src/native_host/types.rs index 5249a687f0..2f7f68f324 100644 --- a/crates/sqlbuild-python-base/src/native_host/types.rs +++ b/crates/sqlbuild-python-base/src/native_host/types.rs @@ -14,3 +14,10 @@ pub trait Syntax<'py> { /// One syntax attribute, such as `render_qualified_name`; anything reaching the warehouse is refused. fn syntax(&self, name: &str) -> PyResult>; } + +/// One end of the socket pair Python's wakeup descriptor writes to. +#[cfg(unix)] +pub(crate) type WakeupSocket = std::os::unix::net::UnixStream; +/// One end of the socket pair Python's wakeup descriptor writes to. +#[cfg(windows)] +pub(crate) type WakeupSocket = std::net::TcpStream; diff --git a/crates/sqlbuild-python-base/src/orchestration_reads/main/mask_sensor_outcome.rs b/crates/sqlbuild-python-base/src/orchestration_reads/main/mask_sensor_outcome.rs index adb4ac6a82..ea84e61275 100644 --- a/crates/sqlbuild-python-base/src/orchestration_reads/main/mask_sensor_outcome.rs +++ b/crates/sqlbuild-python-base/src/orchestration_reads/main/mask_sensor_outcome.rs @@ -1,7 +1,7 @@ //! A tick's text with the providers' secret values masked and credential-shaped text redacted, before the location returns it. use pyo3::prelude::{Bound, PyAny, PyResult}; -use sqlbuild_core::redaction::main::redact_text::redact_text; +use sqlbuild_core::redaction::main::redact_masked_text::redact_masked_text; use sqlbuild_orchestration::sensors::models::SensorFunctionOutcome; use crate::orchestration_reads::_helpers::instance_secrets::instance_secret_values; @@ -22,11 +22,11 @@ pub fn mask_sensor_outcome( forms.sort_by(|left, right| right.len().cmp(&left.len()).then_with(|| left.cmp(right))); forms.dedup(); let mask = |text: String| { - redact_text( - &forms - .iter() - .fold(text, |text, form| text.replace(form.as_str(), SECRET_MASK)), - ) + redact_masked_text(&text, |reading| { + forms.iter().fold(reading.to_owned(), |text, form| { + text.replace(form.as_str(), SECRET_MASK) + }) + }) }; Ok(match outcome { SensorFunctionOutcome::Failed { error } => { diff --git a/crates/sqlbuild-python-base/src/orchestration_reads/main/sensor_outcome.rs b/crates/sqlbuild-python-base/src/orchestration_reads/main/sensor_outcome.rs index 7c5c892f68..754eb747b2 100644 --- a/crates/sqlbuild-python-base/src/orchestration_reads/main/sensor_outcome.rs +++ b/crates/sqlbuild-python-base/src/orchestration_reads/main/sensor_outcome.rs @@ -20,7 +20,7 @@ pub fn sensor_outcome( let authoring = py.import(SENSOR_AUTHORING_MODULE)?; if result.is_instance(&authoring.getattr("SkipReason")?)? { let reason: String = result.getattr("reason")?.extract()?; - if reason.trim().is_empty() { + if reason.replace('\0', "").trim().is_empty() { return Err(PyValueError::new_err("SkipReason needs a nonempty reason")); } return Ok(SensorFunctionOutcome::Skipped { cursor, reason }); diff --git a/crates/sqlbuild-python-base/src/records/_helpers/compile_records/constants.rs b/crates/sqlbuild-python-base/src/records/_helpers/compile_records/constants.rs index d2a20b07f4..b91bfa0d5e 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/compile_records/constants.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/compile_records/constants.rs @@ -975,6 +975,20 @@ const R_DISCOVERED_ASSET_FUNCTION: RecordSpec = RecordSpec { compared: false, shown: false, }, + FieldSpec::new("for_each", FieldDefault::None), + FieldSpec::new("discovered", FieldDefault::None), + ], +}; +const R_DISCOVERED_DISCOVER_FUNCTION: RecordSpec = RecordSpec { + name: "DiscoveredDiscoverFunction", + doc: "A discovered project function that discovers a set of items at publish.", + fields: &[ + FieldSpec::required("file_path"), + FieldSpec::required("relative_path"), + FieldSpec::required("name"), + FieldSpec::required("function"), + FieldSpec::new("check_every_seconds", FieldDefault::None), + FieldSpec::new("provider_usages", FieldDefault::EmptyTuple), ], }; const R_DISCOVERED_CHECK_FUNCTION: RecordSpec = RecordSpec { @@ -1117,6 +1131,8 @@ const R_DISCOVERED_PYTHON_NODE_FUNCTIONS: RecordSpec = RecordSpec { FieldSpec::new("assets", FieldDefault::EmptyTuple), FieldSpec::new("checks", FieldDefault::EmptyTuple), FieldSpec::new("audit_factories", FieldDefault::EmptyTuple), + FieldSpec::new("discover_functions", FieldDefault::EmptyTuple), + FieldSpec::new("for_each_assets", FieldDefault::EmptyTuple), ], }; const R_DISCOVERED_PROJECT_INPUTS: RecordSpec = RecordSpec { @@ -1144,6 +1160,8 @@ const R_DISCOVERED_PROJECT_INPUTS: RecordSpec = RecordSpec { FieldSpec::new("loader_functions", FieldDefault::EmptyTuple), FieldSpec::new("asset_functions", FieldDefault::EmptyTuple), FieldSpec::new("check_functions", FieldDefault::EmptyTuple), + FieldSpec::new("discover_functions", FieldDefault::EmptyTuple), + FieldSpec::new("for_each_assets", FieldDefault::EmptyTuple), FieldSpec::new("audit_factories", FieldDefault::EmptyTuple), FieldSpec::new("hook_functions", FieldDefault::EmptyTuple), FieldSpec::new("event_exporters", FieldDefault::EmptyTuple), @@ -1685,6 +1703,7 @@ pub(crate) const COMPILE_VALUE_RECORDS: &[RecordSpec] = &[ R_DISCOVERED_PROVIDER_USAGE, R_DISCOVERED_LOADER_FUNCTION, R_DISCOVERED_ASSET_FUNCTION, + R_DISCOVERED_DISCOVER_FUNCTION, R_DISCOVERED_CHECK_FUNCTION, R_DISCOVERED_HOOK_FUNCTION, R_DISCOVERED_AUDIT_FACTORY, diff --git a/crates/sqlbuild-python-base/src/records/_helpers/compiler_records/constants.rs b/crates/sqlbuild-python-base/src/records/_helpers/compiler_records/constants.rs index ad3464a5d9..a5501f0272 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/compiler_records/constants.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/compiler_records/constants.rs @@ -510,6 +510,7 @@ const R_DISCOVERED_PYTHON_ASSET_METADATA: RecordSpec = RecordSpec { FieldSpec::new("columns", FieldDefault::EmptyTuple), FieldSpec::new("column_lineage", FieldDefault::None), FieldSpec::new("retry", FieldDefault::None), + FieldSpec::new("discovered", FieldDefault::None), ], }; const R_DISCOVERED_PYTHON_CHECK_METADATA: RecordSpec = RecordSpec { diff --git a/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs b/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs index 51f1ec8673..e195926e7c 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/native_classes/ids.rs @@ -207,6 +207,7 @@ native_id_names! { RecordId::DiscoveredCommandOutputSink => "DiscoveredCommandOutputSink", RecordId::DiscoveredCommandOutputSinkDeclaration => "DiscoveredCommandOutputSinkDeclaration", RecordId::DiscoveredConstantFile => "DiscoveredConstantFile", + RecordId::DiscoveredDiscoverFunction => "DiscoveredDiscoverFunction", RecordId::DiscoveredEnumFile => "DiscoveredEnumFile", RecordId::DiscoveredEventExporter => "DiscoveredEventExporter", RecordId::DiscoveredEventExporterDeclaration => "DiscoveredEventExporterDeclaration", diff --git a/crates/sqlbuild-python-base/src/records/types.rs b/crates/sqlbuild-python-base/src/records/types.rs index 8893ea9fe9..ce28b138cf 100644 --- a/crates/sqlbuild-python-base/src/records/types.rs +++ b/crates/sqlbuild-python-base/src/records/types.rs @@ -200,6 +200,7 @@ pub enum RecordId { DiscoveredCommandOutputSink, DiscoveredCommandOutputSinkDeclaration, DiscoveredConstantFile, + DiscoveredDiscoverFunction, DiscoveredEnumFile, DiscoveredEventExporter, DiscoveredEventExporterDeclaration, diff --git a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs index 00494c1a25..b49885f80b 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/stages/discovery.rs @@ -21,6 +21,7 @@ use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_front::compile_driver::main::reject_invalid_project_configuration::reject_invalid_project_configuration; use sqlbuild_python_front::compile_driver::models::ProjectConfiguration; +use sqlbuild_python_front::discovered_sets::main::with_discovered_sets::with_discovered_sets; use sqlbuild_python_front::discovery::constants::{ ALLOW_MISSING_SECRETS_ENV, ALLOW_MISSING_SECRETS_SETTING, TRUE_ENV_VALUES, }; @@ -293,6 +294,7 @@ pub(crate) fn assembled_inputs<'py>( ), secret_policy, )?; + let discovered: Bound<'py, PyAny> = with_discovered_sets(&discovered)?; host_entry(py, UserCodeHost::ValidateDiscoveredInputs)?.call1((&discovered,))?; configure_discovered_event_exporters(&discovered)?; Ok(discovered) @@ -512,6 +514,8 @@ fn project_inputs<'py>( fields.push(("loader_functions", loader_functions)); fields.push(("asset_functions", tuple_of("assets")?)); fields.push(("check_functions", tuple_of("checks")?)); + fields.push(("discover_functions", tuple_of("discover_functions")?)); + fields.push(("for_each_assets", tuple_of("for_each_assets")?)); fields.push(("audit_factories", tuple_of("audit_factories")?)); for field in [ "hook_functions", diff --git a/crates/sqlbuild-python-compile/src/input_loops/_helpers/model/model_loop_hooks.rs b/crates/sqlbuild-python-compile/src/input_loops/_helpers/model/model_loop_hooks.rs index 23aee1c7db..e96cfe6f75 100644 --- a/crates/sqlbuild-python-compile/src/input_loops/_helpers/model/model_loop_hooks.rs +++ b/crates/sqlbuild-python-compile/src/input_loops/_helpers/model/model_loop_hooks.rs @@ -305,22 +305,26 @@ impl<'py> HookRun<'_, '_, 'py> { let owner: String = format!("{} {label}", scope.file_path); let definition_label: String = format!("SQL hook '{name}' in {}", definition_path.str()?.to_str()?); - let rendered: String = render_parameterized_sql(&body, &argument_pairs(&kwargs)?, true) - .map_err(|stop| { - let message: String = match stop { - ParameterRenderStop::UnusedArguments(names) => format!( - "{owner} passes unknown argument(s) to {definition_label}: {}", - names.join(", ") - ), - ParameterRenderStop::MissingArgument(argument) => { - format!("{owner} is missing argument '{argument}' for {definition_label}") - } - ParameterRenderStop::UnsupportedValue(argument) => format!( - "{owner} {definition_label} argument '{argument}' uses an unsupported value" - ), - }; - compile_error(self.context.classes, &message, None) - })?; + let rendered: String = render_parameterized_sql( + &body, + &argument_pairs(&kwargs)?, + (true, Some(self.context.syntax)), + ) + .map_err(|stop| { + let message: String = match stop { + ParameterRenderStop::UnusedArguments(names) => format!( + "{owner} passes unknown argument(s) to {definition_label}: {}", + names.join(", ") + ), + ParameterRenderStop::MissingArgument(argument) => { + format!("{owner} is missing argument '{argument}' for {definition_label}") + } + ParameterRenderStop::UnsupportedValue(argument) => format!( + "{owner} {definition_label} argument '{argument}' uses an unsupported value" + ), + }; + compile_error(self.context.classes, &message, None) + })?; let start: usize = self.references.borrow().len(); let hook_path: String = native_field(&definition, FILE_PATH_ATTRIBUTE)? .str()? diff --git a/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/audit_loop.rs b/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/audit_loop.rs index bfa98184c6..58818cf809 100644 --- a/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/audit_loop.rs +++ b/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/audit_loop.rs @@ -406,21 +406,25 @@ impl<'py> AuditScope<'_, 'py> { if let Some(column) = column { implicit.push((COLUMN_ARGUMENT.to_owned(), column.to_owned())); } - let rendering: AuditRendering = render_attached_audit(&AuditAttachment { - owner_label: owner_file.to_owned(), - definition_name: definition_name.clone(), - definition_path: (!definition.builtin).then(|| definition.file.relative_path.clone()), - sql_body: definition.block.sql_body.clone(), - evidence_sql: definition.block.evidence_sql.clone(), - implicit_arguments: implicit, - explicit_arguments: instance.arguments()?, - has_thresholds, - threshold_error, - instance_severity, - default_severity: self.settings.default_severity.clone(), - instance_run_scope: instance.field("run_scope")?.extract()?, - default_run_scope: self.settings.default_run_scope.clone(), - }); + let rendering: AuditRendering = render_attached_audit( + &AuditAttachment { + owner_label: owner_file.to_owned(), + definition_name: definition_name.clone(), + definition_path: (!definition.builtin) + .then(|| definition.file.relative_path.clone()), + sql_body: definition.block.sql_body.clone(), + evidence_sql: definition.block.evidence_sql.clone(), + implicit_arguments: implicit, + explicit_arguments: instance.arguments()?, + has_thresholds, + threshold_error, + instance_severity, + default_severity: self.settings.default_severity.clone(), + instance_run_scope: instance.field("run_scope")?.extract()?, + default_run_scope: self.settings.default_run_scope.clone(), + }, + Some(&self.model_loop.syntax), + ); let rendered = match rendering { AuditRendering::Failed(message) => { return Err(compile_error(self.context.classes, &message, None)); diff --git a/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/sql_test_loop.rs b/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/sql_test_loop.rs index 37a66c1c5b..111e822cc3 100644 --- a/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/sql_test_loop.rs +++ b/crates/sqlbuild-python-compile/src/input_loops/_helpers/resources/sql_test_loop.rs @@ -34,6 +34,7 @@ use sqlbuild_render::macro_calls::main::macro_call_names::macro_call_names; use sqlbuild_sqltext::compiler::models::DeclarationReferenceStop; use sqlbuild_sqltext::sql_references::main::extract_sql_references::extract_sql_references; use sqlbuild_sqltext::sql_references::models::{ReferenceExtraction, SqlReference}; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; use crate::input_loops::_helpers::model::model_loop::LoopContext; @@ -229,26 +230,46 @@ impl<'py> TestScope<'_, 'py> { let declared: Vec = values.iter().map(|(name, _)| name.clone()).collect(); let owner: String = format!("SQL test '{test_name}' case '{case_name}' in '{file_path}'"); let scan = parameter_references(sql, &declared, &owner); - let characters: Vec = sql.chars().collect(); + let offsets: Vec = sql + .char_indices() + .map(|(offset, _)| offset) + .chain([sql.len()]) + .collect(); let mut expanded: String = String::with_capacity(sql.len()); let mut cursor: usize = 0; let mut used: HashSet<&str> = HashSet::new(); + let mut texts: Vec = Vec::with_capacity(scan.references.len()); for reference in &scan.references { - expanded.extend(&characters[cursor..reference.start]); let value: &Py = values .iter() .find(|(name, _)| *name == reference.name) .map(|(_, value)| value) .ok_or_else(|| self.error(&reference.name))?; - expanded.push_str(&self.rendered_parameter( - (test_name, case_name), - &reference.name, - value, - )?); + texts.push(self.rendered_parameter((test_name, case_name), &reference.name, value)?); used.insert(&reference.name); - cursor = reference.end; } - expanded.extend(&characters[cursor..]); + let sites: Vec<(usize, usize, &str)> = scan + .references + .iter() + .zip(&texts) + .map(|(reference, text)| { + ( + offsets[reference.start], + offsets[reference.end], + text.as_str(), + ) + }) + .collect(); + let bounded = bounded_expansions(sql, &sites, Some(&self.model_loop.syntax)); + for expansion in bounded { + texts[expansion.index] = expansion.text; + } + for (reference, text) in scan.references.iter().zip(&texts) { + expanded.push_str(&sql[cursor..offsets[reference.start]]); + expanded.push_str(text); + cursor = offsets[reference.end]; + } + expanded.push_str(&sql[cursor..]); if let Some(message) = scan.error { return Err(self.error(&message)); } diff --git a/crates/sqlbuild-python-compile/src/provider_check/main/secret_block_error.rs b/crates/sqlbuild-python-compile/src/provider_check/main/secret_block_error.rs index f6c64ee772..2f831ff3f3 100644 --- a/crates/sqlbuild-python-compile/src/provider_check/main/secret_block_error.rs +++ b/crates/sqlbuild-python-compile/src/provider_check/main/secret_block_error.rs @@ -3,8 +3,11 @@ use std::path::Path; use pyo3::prelude::{PyErr, Python}; +use sqlbuild_core::process_environment::main::location_secret_fix::location_secret_fix; +use sqlbuild_core::process_environment::main::shell_secret_fix::shell_secret_fix; use sqlbuild_python_base::records::main::construct::new_annotated_error::new_annotated_error; use sqlbuild_python_base::records::types::ErrorId; +use sqlbuild_python_front::discovery::main::sources::env_file_display::env_file_display; use sqlbuild_python_front::discovery::main::sources::secret_places::secret_places; use crate::provider_check::_helpers::text::{rows, sink_lines}; @@ -32,10 +35,14 @@ pub fn secret_block_error(py: Python<'_>, blocks: &[SecretBlock], project_dir: & .into_iter() .map(|line| format!(" {line}")), ); - let help: &str = if std::env::var_os(RUN_TOKEN_VARIABLE).is_some() { - "set each variable in the location's environment (or its env file) and restart the location; the next run then works" + let env_file: Option = env_file_display(project_dir); + let help: String = if std::env::var_os(RUN_TOKEN_VARIABLE).is_some() { + location_secret_fix("each variable", env_file.as_deref()) } else { - "set each variable in this shell or the project's env file, or narrow the selection" + format!( + "{}, or narrow the selection", + shell_secret_fix("each variable", env_file.as_deref()) + ) }; new_annotated_error( py, @@ -45,6 +52,6 @@ pub fn secret_block_error(py: Python<'_>, blocks: &[SecretBlock], project_dir: & secret_places(project_dir), lines.join("\n") ), - &[("help", help.to_owned())], + &[("help", help)], ) } diff --git a/crates/sqlbuild-python-front/Cargo.toml b/crates/sqlbuild-python-front/Cargo.toml index a89a503d5e..27062b517d 100644 --- a/crates/sqlbuild-python-front/Cargo.toml +++ b/crates/sqlbuild-python-front/Cargo.toml @@ -31,6 +31,7 @@ sqlbuild-scopes.workspace = true sqlbuild-sqltext.workspace = true sqlbuild-state.workspace = true stacker.workspace = true +tokio.workspace = true uuid.workspace = true [lints] diff --git a/crates/sqlbuild-python-front/src/attachments/_helpers/cursor_intrinsics.rs b/crates/sqlbuild-python-front/src/attachments/_helpers/cursor_intrinsics.rs index c26925d74b..2711ebb598 100644 --- a/crates/sqlbuild-python-front/src/attachments/_helpers/cursor_intrinsics.rs +++ b/crates/sqlbuild-python-front/src/attachments/_helpers/cursor_intrinsics.rs @@ -9,6 +9,7 @@ use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; use pyo3::types::{PyString, PyStringMethods}; use pyo3::{Python, pyfunction}; use sqlbuild_attachments::cursor_intrinsics::main::replace_intrinsics::replace_intrinsics; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; use sqlbuild_python_base::boundary::main::compiler_guard::compiler_guard; @@ -33,6 +34,39 @@ pub(crate) fn text_value(value: &Bound<'_, PyAny>) -> Option { } } +/// `sql` with the cursor markers replaced by concrete bounds, none joining a neighbour into a comment. +#[pyfunction] +#[pyo3(signature = (*, sql, start_sql, end_sql))] +pub(crate) fn replace_cursor_markers(sql: &str, start_sql: &str, end_sql: &str) -> String { + let mut sites: Vec<(usize, usize, &str)> = Vec::new(); + for (marker, value) in RESERVED_CURSOR_MARKERS + .into_iter() + .zip([start_sql, end_sql]) + { + sites.extend( + sql.match_indices(marker) + .map(|(position, found)| (position, position + found.len(), value)), + ); + } + sites.sort_unstable_by_key(|(position, _, _)| *position); + let mut texts: Vec = sites + .iter() + .map(|(_, _, value)| (*value).to_owned()) + .collect(); + for bounded in bounded_expansions(sql, &sites, None) { + texts[bounded.index] = bounded.text; + } + let mut replaced: String = String::with_capacity(sql.len()); + let mut copied: usize = 0; + for ((position, after, _), text) in sites.iter().zip(&texts) { + replaced.push_str(&sql[copied..*position]); + replaced.push_str(text); + copied = *after; + } + replaced.push_str(&sql[copied..]); + replaced +} + /// `sql` with each intrinsic replaced by its bound and whether any was, raising for `context`. pub(crate) fn replaced( py: Python<'_>, diff --git a/crates/sqlbuild-python-front/src/attachments/main/register_reference_markers.rs b/crates/sqlbuild-python-front/src/attachments/main/register_reference_markers.rs index 9e9a25e353..a99447d4fb 100644 --- a/crates/sqlbuild-python-front/src/attachments/main/register_reference_markers.rs +++ b/crates/sqlbuild-python-front/src/attachments/main/register_reference_markers.rs @@ -1,5 +1,6 @@ //! Register the reference markers functions and classes. +use crate::attachments::_helpers::cursor_intrinsics::replace_cursor_markers; use crate::attachments::main::assert_no_unresolved_sql_markers::assert_no_unresolved_sql_markers; use pyo3::prelude::{Bound, PyModule, PyModuleMethods, PyResult}; use pyo3::wrap_pyfunction; @@ -7,5 +8,6 @@ use pyo3::wrap_pyfunction; /// Register the reference markers functions and classes. pub fn register_reference_markers(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add_function(wrap_pyfunction!(assert_no_unresolved_sql_markers, module)?)?; + module.add_function(wrap_pyfunction!(replace_cursor_markers, module)?)?; Ok(()) } diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/discover_files.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/discover_files.rs new file mode 100644 index 0000000000..7e094fcb3b --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/discover_files.rs @@ -0,0 +1,20 @@ +//! The file each discover function is defined in, so a location reruns only what an edit touched. + +use std::collections::BTreeMap; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +/// Each discover function's name with its file, as a POSIX path relative to the project. +pub(crate) fn discover_files(inputs: &Bound<'_, PyAny>) -> PyResult> { + let mut files: BTreeMap = BTreeMap::new(); + for record in native_field(inputs, "discover_functions")?.try_iter()? { + let record: Bound<'_, PyAny> = record?; + let path: String = native_field(&record, "relative_path")? + .str()? + .to_string() + .replace('\\', "/"); + files.insert(native_field(&record, "name")?.extract()?, path); + } + Ok(files) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/item_records.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/item_records.rs new file mode 100644 index 0000000000..14bc71fbfc --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/item_records.rs @@ -0,0 +1,166 @@ +//! The asset records of each `for_each` asset: one per item of its set, or one placeholder. + +use std::collections::BTreeSet; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; +use pyo3::types::{PyString, PyTuple}; +use serde_json::{Value, json}; +use sqlbuild_host::entries::models::UserCodeHost; +use sqlbuild_orchestration::discovered_sets::main::item_node_name::item_node_name; +use sqlbuild_orchestration::discovered_sets::main::item_roots::item_roots; +use sqlbuild_orchestration::discovered_sets::models::{ + DiscoveredItem, DiscoveredResult, ItemDependency, +}; +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; +use sqlbuild_python_base::boundary::main::call_with::call_with; +use sqlbuild_python_base::boundary::main::json_value_to_python::json_value_to_python; +use sqlbuild_python_base::native_host::main::host_entry::host_entry; +use sqlbuild_python_base::records::main::construct::new_plain_error::new_plain_error; +use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_base::records::main::fields::replaced::replaced; +use sqlbuild_python_base::records::types::ErrorId; + +use crate::discovery::main::python_files::node_identity::node_identity; + +const ASSET_IDENTITY: (&str, bool) = ("ASSET", true); + +/// The project's assets with each `for_each` asset expanded from `sets`. +pub(crate) fn expanded_assets<'py>( + inputs: &Bound<'py, PyAny>, + sets: &DiscoveredSets, +) -> PyResult>> { + let py: Python<'py> = inputs.py(); + let mut assets: Vec> = Vec::new(); + for asset in native_field(inputs, "asset_functions")?.try_iter()? { + let asset: Bound<'py, PyAny> = asset?; + if native_field(&asset, "discovered")?.is_none() { + assets.push(asset); + } + } + for template in native_field(inputs, "for_each_assets")?.try_iter()? { + let template: Bound<'py, PyAny> = template?; + let asset: String = native_field(&template, "name")?.extract()?; + let set_name: String = native_field(&template, "for_each")?.extract()?; + let Some(set) = sets.get(&set_name) else { + return Err(new_plain_error( + py, + ErrorId::PythonNodeDiscovery, + &format!( + "Asset '{asset}' runs for_each '{set_name}', but no @discover function is named '{set_name}'" + ), + )); + }; + let names = (asset.as_str(), set_name.as_str()); + match &set.result { + Some(result) => { + let roots: BTreeSet = item_roots(result); + for item in &result.items { + let root: bool = roots.contains(&item.id); + assets.push(item_record(&template, names, (result, item, root))?); + } + } + None => assets.push(placeholder_record(&template, names, set.error.as_deref())?), + } + } + Ok(assets) +} + +/// One item's asset: named `[]`, waiting on its items, or on the asset's own dependencies at a root. +fn item_record<'py>( + template: &Bound<'py, PyAny>, + (asset, set_name): (&str, &str), + (result, item, root): (&DiscoveredResult, &DiscoveredItem, bool), +) -> PyResult> { + let py: Python<'py> = template.py(); + let mut depends_on: Vec> = Vec::new(); + if root { + for dependency in native_field(template, "depends_on")?.try_iter()? { + depends_on.push(dependency?); + } + } + let references: Bound<'py, PyAny> = call_with( + &host_entry(py, UserCodeHost::ItemDependencyRefs)?, + &[( + "depends_on", + json_value_to_python(py, &dependencies_json(asset, &item.depends_on))?, + )], + )?; + for reference in references.try_iter()? { + depends_on.push(reference?); + } + let discovered: Value = json!({ + "asset": asset, + "set": set_name, + "item": item.id, + "args": item.args, + "tags": result.tags, + "max_parallel": result.max_parallel, + "placeholder": false, + "error": null, + }); + named_record( + template, + &item_node_name(asset, Some(&item.id)), + (PyTuple::new(py, depends_on)?.into_any(), &discovered), + ) +} + +/// The one node of a set that never succeeded: `[*]`, waiting on the asset's own dependencies. +fn placeholder_record<'py>( + template: &Bound<'py, PyAny>, + (asset, set_name): (&str, &str), + error: Option<&str>, +) -> PyResult> { + let discovered: Value = json!({ + "asset": asset, + "set": set_name, + "item": null, + "args": {}, + "tags": {}, + "max_parallel": null, + "placeholder": true, + "error": error, + }); + named_record( + template, + &item_node_name(asset, None), + (native_field(template, "depends_on")?, &discovered), + ) +} + +/// `template` renamed `name`, with `depends_on` and `discovered`, and its identity read again. +fn named_record<'py>( + template: &Bound<'py, PyAny>, + name: &str, + (depends_on, discovered): (Bound<'py, PyAny>, &Value), +) -> PyResult> { + let py: Python<'py> = template.py(); + let record: Bound<'py, PyAny> = replaced( + template, + &[ + ("name", PyString::new(py, name).into_any()), + ("depends_on", depends_on), + ("discovered", json_value_to_python(py, discovered)?), + ], + )?; + let identity: Bound<'py, PyAny> = + node_identity(py, ASSET_IDENTITY, &|field| native_field(&record, field))?; + replaced(&record, &[("identity", identity)]) +} + +/// An item's dependencies as saved JSON, its sibling items named by their nodes. +fn dependencies_json(asset: &str, dependencies: &[ItemDependency]) -> Value { + Value::Array( + dependencies + .iter() + .map(|dependency| match dependency { + ItemDependency::Item(id) => json!({"item": item_node_name(asset, Some(id))}), + ItemDependency::Model(_) + | ItemDependency::Source(_) + | ItemDependency::Seed(_) + | ItemDependency::Job(_) + | ItemDependency::Tag(_) => json!(dependency), + }) + .collect(), + ) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/live_sets.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/live_sets.rs new file mode 100644 index 0000000000..7183c9137b --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/live_sets.rs @@ -0,0 +1,198 @@ +//! Each discover function's set for one compile: placeholders, saved sets, or a live call. + +use chrono::Utc; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; +use pyo3::types::PyTuple; +use sqlbuild_orchestration::discovered_sets::main::never_discovered::never_discovered; +use sqlbuild_orchestration::discovered_sets::main::record_attempt::record_attempt; +use sqlbuild_orchestration::discovered_sets::main::remote_discovered_sets::remote_discovered_sets; +use sqlbuild_orchestration::discovered_sets::models::{ + DiscoveredResult, DiscoveredSet, DiscoveredSetStatus, +}; +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; +use sqlbuild_python_base::records::main::construct::new_plain_error::new_plain_error; +use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_base::records::types::ErrorId; + +use crate::discovered_sets::_helpers::project_nodes::{missing_node, usable_set}; +use crate::discovered_sets::_helpers::state::RUNNER; +use crate::discovered_sets::models::{DiscoverySource, LiveDiscovery, Rediscover, SeedSource}; + +const ERROR: ErrorId = ErrorId::PythonNodeDiscovery; +/// The location credential a location reads its current snapshot with. +const LOCATION_TOKEN_ENV: &str = "SQLBUILD_LOCATION_TOKEN"; + +/// Every discover function's set under `source`; a repeated name, or a failure outside a location, raises. +pub(crate) fn resolved_sets( + inputs: &Bound<'_, PyAny>, + source: &DiscoverySource, +) -> PyResult { + let py: Python<'_> = inputs.py(); + let mut sets: DiscoveredSets = DiscoveredSets::new(); + for record in native_field(inputs, "discover_functions")?.try_iter()? { + let record: Bound<'_, PyAny> = record?; + let name: String = native_field(&record, "name")?.extract()?; + let check_every: Option = native_field(&record, "check_every_seconds")?.extract()?; + let set: DiscoveredSet = match source { + DiscoverySource::Placeholders => never_discovered(check_every), + DiscoverySource::Saved(saved) => saved.get(&name).cloned().map_or_else( + || never_discovered(check_every), + |set| checked(set, check_every), + ), + DiscoverySource::Live(live) => { + let requested: bool = match &live.rediscover { + Rediscover::All => true, + Rediscover::Only(names) => names.contains(&name), + }; + live_set(inputs, (&record, &name, check_every), (live, requested))? + } + }; + if sets.insert(name.clone(), set).is_some() { + return Err(new_plain_error( + py, + ERROR, + &format!("Two @discover functions are named '{name}'; give one another name"), + )); + } + } + match source { + DiscoverySource::Live(LiveDiscovery { + seed: Some(seed), .. + }) => seeded(py, sets, seed) + .into_iter() + .map(|(name, set)| Ok((name, usable_set(inputs, set)?))) + .collect(), + _ => Ok(sets), + } +} + +/// `sets` with each failed set that has no result given the server's last good one, if any. +fn seeded(py: Python<'_>, mut sets: DiscoveredSets, source: &SeedSource) -> DiscoveredSets { + let unseeded: Vec = sets + .iter() + .filter(|(_, set)| set.status == DiscoveredSetStatus::Failed && set.result.is_none()) + .map(|(name, _)| name.clone()) + .collect(); + if unseeded.is_empty() { + return sets; + } + let server: Result = server_sets(py, source); + for name in unseeded { + let Some(set) = sets.get_mut(&name) else { + continue; + }; + match &server { + Ok(server) => { + if let Some(earlier) = server.get(&name) { + set.result.clone_from(&earlier.result); + set.digest.clone_from(&earlier.digest); + set.last_good_at = earlier.last_good_at; + } + } + Err(reason) => { + set.error = Some(format!( + "{}; its last good items could not be read: {reason}", + set.error.as_deref().unwrap_or("failed") + )); + } + } + } + sets +} + +/// The sets of the server's current snapshot, read with the location credential. +fn server_sets(py: Python<'_>, source: &SeedSource) -> Result { + let bearer: String = std::env::var(LOCATION_TOKEN_ENV) + .map_err(|error| format!("{LOCATION_TOKEN_ENV}: {error}"))?; + py.detach(|| { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| error.to_string())? + .block_on(remote_discovered_sets( + (&source.server_url, &bearer), + (source.location_id, &source.target), + )) + .map_err(|error| error.to_string()) + }) +} + +fn checked(mut set: DiscoveredSet, check_every_seconds: Option) -> DiscoveredSet { + set.check_every_seconds = check_every_seconds; + set +} + +/// The set after calling its function if `requested` or never tried; otherwise the previous set. +pub(crate) fn live_set( + inputs: &Bound<'_, PyAny>, + (record, name, check_every): (&Bound<'_, PyAny>, &str, Option), + (live, requested): (&LiveDiscovery, bool), +) -> PyResult { + let py: Python<'_> = inputs.py(); + let previous: Option<&DiscoveredSet> = live.previous.get(name); + let untried: bool = previous.is_none_or(|set| set.status == DiscoveredSetStatus::Never); + if !requested && !untried { + return usable_set( + inputs, + previous.cloned().map_or_else( + || never_discovered(check_every), + |set| checked(set, check_every), + ), + ); + } + let runner = RUNNER.get().ok_or_else(|| { + new_plain_error( + py, + ERROR, + "this build of SQLBuild cannot run @discover functions", + ) + })?; + let assets = PyTuple::new(py, for_each_functions(inputs, name)?)?; + let project_dir: Bound<'_, PyAny> = native_field(inputs, "project_dir")?; + let attempt: Result = runner( + py, + (&project_dir, live.target.as_deref()), + (record, assets.as_any()), + ) + .and_then(|json| { + serde_json::from_str(&json) + .map_err(|error| format!("discover function returned an unreadable result: {error}")) + }); + let attempt: Result = match attempt { + Ok(result) => match missing_node(inputs, &result)? { + Some(problem) => Err(problem), + None => Ok(result), + }, + Err(error) => Err(error), + }; + let set: DiscoveredSet = usable_set( + inputs, + record_attempt(previous, attempt, (Utc::now(), check_every)), + )?; + if !live.keep_last_good && set.status == DiscoveredSetStatus::Failed { + return Err(new_plain_error( + py, + ERROR, + &format!( + "Discover function '{name}' failed: {}", + set.error.as_deref().unwrap_or("no reason given") + ), + )); + } + Ok(set) +} + +/// The functions of the assets that run once per item of set `name`. +fn for_each_functions<'py>( + inputs: &Bound<'py, PyAny>, + name: &str, +) -> PyResult>> { + let mut functions: Vec> = Vec::new(); + for template in native_field(inputs, "for_each_assets")?.try_iter()? { + let template: Bound<'py, PyAny> = template?; + if native_field(&template, "for_each")?.extract::()? == name { + functions.push(native_field(&template, "function")?); + } + } + Ok(functions) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/mod.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/mod.rs new file mode 100644 index 0000000000..2ad369bd21 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/mod.rs @@ -0,0 +1,6 @@ +pub(crate) mod discover_files; +pub(crate) mod item_records; +pub(crate) mod live_sets; +pub(crate) mod project_nodes; +pub(crate) mod rediscover_set; +pub(crate) mod state; diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/project_nodes.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/project_nodes.rs new file mode 100644 index 0000000000..64c05ece3c --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/project_nodes.rs @@ -0,0 +1,152 @@ +//! The models, sources, seeds and jobs a project declares, which a set's items may depend on. + +use std::collections::BTreeSet; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_orchestration::discovered_sets::main::unknown_dependency::unknown_dependency; +use sqlbuild_orchestration::discovered_sets::models::{ + DiscoveredResult, DiscoveredSet, DiscoveredSetStatus, ItemDependency, +}; +use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_base::records::main::fields::path_stem::path_stem; + +use crate::discovery::main::sources::orchestration_declarations::orchestration_declarations; +use crate::discovery::models::NativeModelFile; + +/// The project's names of each kind an item names; a kind no item names is not read. +struct ProjectNodes { + models: BTreeSet, + sources: BTreeSet, + seeds: BTreeSet, + jobs: BTreeSet, +} + +/// Why `result` can't be a set of the project `inputs` describe, if it can't. +pub(crate) fn missing_node( + inputs: &Bound<'_, PyAny>, + result: &DiscoveredResult, +) -> PyResult> { + let named = |wanted: fn(&ItemDependency) -> bool| { + result + .items + .iter() + .any(|item| item.depends_on.iter().any(wanted)) + }; + let read = |wanted: fn(&ItemDependency) -> bool, + names: fn(&Bound<'_, PyAny>) -> PyResult>| { + if named(wanted) { + names(inputs) + } else { + Ok(BTreeSet::new()) + } + }; + let nodes: ProjectNodes = ProjectNodes { + models: read( + |dependency| matches!(dependency, ItemDependency::Model(_)), + model_names, + )?, + sources: read( + |dependency| matches!(dependency, ItemDependency::Source(_)), + source_names, + )?, + seeds: read( + |dependency| matches!(dependency, ItemDependency::Seed(_)), + seed_names, + )?, + jobs: read( + |dependency| matches!(dependency, ItemDependency::Job(_)), + job_names, + )?, + }; + Ok(unknown_dependency(result, &|dependency| { + nodes.declares(dependency) + })) +} + +/// `set` failed when its result names what the project lacks: its last good items are dropped. +pub(crate) fn usable_set( + inputs: &Bound<'_, PyAny>, + mut set: DiscoveredSet, +) -> PyResult { + let Some(result) = &set.result else { + return Ok(set); + }; + let Some(problem) = missing_node(inputs, result)? else { + return Ok(set); + }; + set.error = Some(match (set.status, set.error.take()) { + (DiscoveredSetStatus::Failed, Some(error)) => { + format!("{error}; its last good items can't be kept: {problem}") + } + _ => problem, + }); + set.status = DiscoveredSetStatus::Failed; + set.result = None; + set.digest = None; + set.last_good_at = None; + Ok(set) +} + +impl ProjectNodes { + fn declares(&self, dependency: &ItemDependency) -> bool { + match dependency { + ItemDependency::Model(name) => self.models.contains(name), + ItemDependency::Source(name) => self.sources.contains(name), + ItemDependency::Seed(name) => self.seeds.contains(name), + ItemDependency::Job(set) => self.jobs.contains(&set.name), + ItemDependency::Item(_) | ItemDependency::Tag(_) => true, + } + } +} + +/// Each model file's name, its file's stem. +fn model_names(inputs: &Bound<'_, PyAny>) -> PyResult> { + let mut names: BTreeSet = BTreeSet::new(); + for file in native_field(inputs, "model_files")?.try_iter()? { + let file: Bound<'_, PyAny> = file?; + names.insert(match file.cast::() { + Ok(native) => native.get().path_texts(file.py())?.name, + Err(_) => path_stem(&native_field(&file, "file_path")?)?, + }); + } + Ok(names) +} + +/// Every declared source, and each loader, which a `+source` selection treats as one. +fn source_names(inputs: &Bound<'_, PyAny>) -> PyResult> { + let mut names: BTreeSet = BTreeSet::new(); + for file in native_field(inputs, "source_files")?.try_iter()? { + for entry in native_field(&file?, "source_entries")?.try_iter()? { + names.insert(native_field(&entry?, "name")?.extract()?); + } + } + for loader in native_field(inputs, "loader_functions")?.try_iter()? { + names.insert(native_field(&loader?, "name")?.extract()?); + } + Ok(names) +} + +/// Each seed CSV's name; discovery checks that each has its declaration. +fn seed_names(inputs: &Bound<'_, PyAny>) -> PyResult> { + let mut names: BTreeSet = BTreeSet::new(); + for file in native_field(inputs, "seed_files")?.try_iter()? { + names.insert(path_stem(&native_field(&file?, "file_path")?)?); + } + Ok(names) +} + +/// Every job and job group under `orchestration/`, whatever targets they are declared for. +fn job_names(inputs: &Bound<'_, PyAny>) -> PyResult> { + let inventory = orchestration_declarations(&native_field(inputs, "project_dir")?)?; + Ok(inventory + .jobs + .iter() + .map(|(_, job)| job.run.name.value.clone()) + .chain( + inventory + .groups + .iter() + .map(|(_, group)| group.run.name.value.clone()), + ) + .collect()) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/rediscover_set.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/rediscover_set.rs new file mode 100644 index 0000000000..40289166ed --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/rediscover_set.rs @@ -0,0 +1,35 @@ +//! One discover function called again, as a location's `check_every` does, without publishing. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_orchestration::discovered_sets::models::DiscoveredSet; +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; + +use crate::discovered_sets::_helpers::live_sets::live_set; +use crate::discovered_sets::models::{LiveDiscovery, Rediscover}; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +/// Set `name` after calling its function again; `None` when no discover function has that name. +pub(crate) fn rediscover_set( + inputs: &Bound<'_, PyAny>, + (name, previous): (&str, Option), + target: Option, +) -> PyResult> { + for record in native_field(inputs, "discover_functions")?.try_iter()? { + let record: Bound<'_, PyAny> = record?; + if native_field(&record, "name")?.extract::()? != name { + continue; + } + let check_every: Option = native_field(&record, "check_every_seconds")?.extract()?; + let live = LiveDiscovery { + target, + previous: previous + .map(|set| DiscoveredSets::from([(name.to_owned(), set)])) + .unwrap_or_default(), + rediscover: Rediscover::All, + keep_last_good: true, + seed: None, + }; + return live_set(inputs, (&record, name, check_every), (&live, true)).map(Some); + } + Ok(None) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/_helpers/state.rs b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/state.rs new file mode 100644 index 0000000000..41aa8ea0a2 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/_helpers/state.rs @@ -0,0 +1,15 @@ +//! The process's discovery source, the sets its last compile used, and the registered runner. + +use std::sync::{Mutex, OnceLock}; + +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; + +use crate::discovered_sets::models::DiscoverySource; +use crate::discovered_sets::types::DiscoverRunner; + +/// The source the next compiles expand from; `None` until a command sets one. +pub(crate) static SOURCE: Mutex> = Mutex::new(None); +/// The sets the newest expansion used. +pub(crate) static USED: Mutex> = Mutex::new(None); +/// The function that calls a discover function with a target's providers. +pub(crate) static RUNNER: OnceLock = OnceLock::new(); diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/checked_set.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/checked_set.rs new file mode 100644 index 0000000000..988226f06b --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/checked_set.rs @@ -0,0 +1,32 @@ +//! A location runtime's `check_every` check of one discovered set. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_orchestration::discovered_sets::main::result_changed::result_changed; +use sqlbuild_orchestration::discovered_sets::models::{DiscoveredSetCheck, DiscoveredSetChecked}; +use sqlbuild_python_base::boundary::models::KeywordArguments; + +use crate::discovered_sets::_helpers::rediscover_set::rediscover_set; + +/// Call one discover function again and say whether its result changed; nothing is published. +pub fn checked_set( + arguments: &KeywordArguments<'_>, + held: Option<&Bound<'_, PyAny>>, + check: DiscoveredSetCheck, +) -> PyResult { + let Some(discovered) = held else { + return Ok(DiscoveredSetChecked { + set: None, + changed: false, + }); + }; + let target: String = arguments.value("selected_target")?.extract()?; + let set = rediscover_set( + discovered, + (&check.check_discovered, check.previous.clone()), + Some(target), + )?; + let changed: bool = set + .as_ref() + .is_some_and(|set| result_changed(check.previous.as_ref(), set)); + Ok(DiscoveredSetChecked { set, changed }) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/discover_for_publication.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/discover_for_publication.rs new file mode 100644 index 0000000000..d1326eca56 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/discover_for_publication.rs @@ -0,0 +1,39 @@ +//! A location runtime's live discovery for the publication it is asked for. + +use pyo3::exceptions::PyValueError; +use pyo3::prelude::{PyAnyMethods, PyResult}; +use sqlbuild_orchestration::discovered_sets::models::DiscoveryPublishRequest; +use sqlbuild_python_base::boundary::models::KeywordArguments; + +use crate::discovered_sets::main::set_discovery_source::set_discovery_source; +use crate::discovered_sets::models::{DiscoverySource, LiveDiscovery, Rediscover, SeedSource}; + +/// Discover live for the publication `request` asks for: its functions called again, the rest reused. +pub fn discover_for_publication( + arguments: &KeywordArguments<'_>, + request: DiscoveryPublishRequest, +) -> PyResult<()> { + let target: String = arguments.value("selected_target")?.extract()?; + let location_id = arguments + .value("location_id")? + .extract::()? + .parse() + .map_err(|_| PyValueError::new_err("location ID must be a UUID"))?; + let seed: Option = if request.seed { + Some(SeedSource { + server_url: arguments.value("server_url")?.extract()?, + location_id, + target: target.clone(), + }) + } else { + None + }; + set_discovery_source(DiscoverySource::Live(LiveDiscovery { + target: Some(target), + previous: request.previous, + rediscover: request.rediscover.map_or(Rediscover::All, Rediscover::Only), + keep_last_good: true, + seed, + })); + Ok(()) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/mod.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/mod.rs new file mode 100644 index 0000000000..ce9f2872b6 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/mod.rs @@ -0,0 +1,8 @@ +pub mod checked_set; +pub mod discover_for_publication; +pub mod publish_only_placeholders; +pub mod published_sets; +pub mod register_discover_runner; +pub mod set_discovery_source; +pub mod used_discovered_sets; +pub mod with_discovered_sets; diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/publish_only_placeholders.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/publish_only_placeholders.rs new file mode 100644 index 0000000000..6ab2231841 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/publish_only_placeholders.rs @@ -0,0 +1,36 @@ +//! The placeholders a command selected to run while it cannot discover them. + +use std::sync::PoisonError; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; + +use crate::discovered_sets::_helpers::state::SOURCE; +use crate::discovered_sets::models::DiscoverySource; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +/// The `for_each` assets among `selected` names that compiled as placeholders outside a location. +pub fn publish_only_placeholders( + inputs: &Bound<'_, PyAny>, + selected: &Bound<'_, PyAny>, +) -> PyResult> { + let outside_location: bool = matches!( + *SOURCE.lock().unwrap_or_else(PoisonError::into_inner), + None | Some(DiscoverySource::Placeholders) + ); + let mut assets: Vec = Vec::new(); + if !outside_location { + return Ok(assets); + } + for asset in native_field(inputs, "asset_functions")?.try_iter()? { + let asset: Bound<'_, PyAny> = asset?; + let discovered: Bound<'_, PyAny> = native_field(&asset, "discovered")?; + if discovered.is_none() + || !discovered.get_item("placeholder")?.is_truthy()? + || !selected.contains(native_field(&asset, "name")?)? + { + continue; + } + assets.push(discovered.get_item("asset")?.extract()?); + } + Ok(assets) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/published_sets.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/published_sets.rs new file mode 100644 index 0000000000..b146844b71 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/published_sets.rs @@ -0,0 +1,22 @@ +//! The sets a location runtime's publication used, kept for its later compiles. + +use std::collections::BTreeMap; + +use pyo3::prelude::{Bound, PyAny, PyResult}; +use serde_json::{Value, json}; + +use crate::discovered_sets::_helpers::discover_files::discover_files; +use crate::discovered_sets::main::set_discovery_source::set_discovery_source; +use crate::discovered_sets::main::used_discovered_sets::used_discovered_sets; +use crate::discovered_sets::models::DiscoverySource; + +/// After a publication, its sets for later compiles and the reply, with each function's file. +pub fn published_sets(held: Option<&Bound<'_, PyAny>>) -> PyResult<(Value, Value)> { + let sets = used_discovered_sets(); + set_discovery_source(DiscoverySource::Saved(sets.clone())); + let files: BTreeMap = match held { + Some(discovered) => discover_files(discovered)?, + None => BTreeMap::new(), + }; + Ok((json!(sets), json!(files))) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/register_discover_runner.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/register_discover_runner.rs new file mode 100644 index 0000000000..4d25106f47 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/register_discover_runner.rs @@ -0,0 +1,9 @@ +//! The function that calls a discover function with a target's providers, registered once. + +use crate::discovered_sets::_helpers::state::RUNNER; +use crate::discovered_sets::types::DiscoverRunner; + +/// Use `runner` to call discover functions; the first registration wins. +pub fn register_discover_runner(runner: DiscoverRunner) { + let _ = RUNNER.set(runner); +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/set_discovery_source.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/set_discovery_source.rs new file mode 100644 index 0000000000..7e57eea55f --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/set_discovery_source.rs @@ -0,0 +1,11 @@ +//! Where the next compiles of this process take their discovered sets from. + +use std::sync::PoisonError; + +use crate::discovered_sets::_helpers::state::SOURCE; +use crate::discovered_sets::models::DiscoverySource; + +/// Expand `for_each` assets from `source` until another source is set. +pub fn set_discovery_source(source: DiscoverySource) { + *SOURCE.lock().unwrap_or_else(PoisonError::into_inner) = Some(source); +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/used_discovered_sets.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/used_discovered_sets.rs new file mode 100644 index 0000000000..7665512079 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/used_discovered_sets.rs @@ -0,0 +1,15 @@ +//! The discovered sets the newest compile of this process used. + +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; + +use std::sync::PoisonError; + +use crate::discovered_sets::_helpers::state::USED; + +/// The sets the newest expansion used; empty before any compile. +pub fn used_discovered_sets() -> DiscoveredSets { + USED.lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + .unwrap_or_default() +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/main/with_discovered_sets.rs b/crates/sqlbuild-python-front/src/discovered_sets/main/with_discovered_sets.rs new file mode 100644 index 0000000000..0871b67bb6 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/main/with_discovered_sets.rs @@ -0,0 +1,32 @@ +//! Discovered project inputs with every `for_each` asset expanded from the process's discovery source. + +use std::sync::PoisonError; + +use pyo3::prelude::{Bound, PyAny, PyResult, Python}; +use pyo3::types::PyTuple; +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; +use sqlbuild_python_base::native_host::main::within_identity_pass::within_identity_pass; +use sqlbuild_python_base::records::main::fields::replaced::replaced; + +use crate::discovered_sets::_helpers::item_records::expanded_assets; +use crate::discovered_sets::_helpers::live_sets::resolved_sets; +use crate::discovered_sets::_helpers::state::{SOURCE, USED}; +use crate::discovered_sets::models::DiscoverySource; + +/// `inputs` with each `for_each` asset as one asset per item of its set, or as its placeholder. +pub fn with_discovered_sets<'py>(inputs: &Bound<'py, PyAny>) -> PyResult> { + let py: Python<'py> = inputs.py(); + let source: DiscoverySource = SOURCE + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + .unwrap_or_default(); + let sets: DiscoveredSets = resolved_sets(inputs, &source)?; + let assets: Vec> = + within_identity_pass(py, || expanded_assets(inputs, &sets))?; + *USED.lock().unwrap_or_else(PoisonError::into_inner) = Some(sets); + replaced( + inputs, + &[("asset_functions", PyTuple::new(py, assets)?.into_any())], + ) +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/mod.rs b/crates/sqlbuild-python-front/src/discovered_sets/mod.rs new file mode 100644 index 0000000000..3d3da3e3ef --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/mod.rs @@ -0,0 +1,6 @@ +//! Discovered sets at compile: each `for_each` asset as one node per item, or a placeholder. + +pub(crate) mod _helpers; +pub mod main; +pub mod models; +pub mod types; diff --git a/crates/sqlbuild-python-front/src/discovered_sets/models.rs b/crates/sqlbuild-python-front/src/discovered_sets/models.rs new file mode 100644 index 0000000000..910138e260 --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/models.rs @@ -0,0 +1,47 @@ +//! Where a compile's discovered sets come from. + +use std::collections::BTreeSet; + +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; +use uuid::Uuid; + +/// The sets a compile expands `for_each` assets from. +#[derive(Clone, Debug, Default)] +pub enum DiscoverySource { + /// No sets: every `for_each` asset is its placeholder node, as outside a location. + #[default] + Placeholders, + /// The sets a publication saved, as a worker compiles them. + Saved(DiscoveredSets), + /// Call discover functions now. + Live(LiveDiscovery), +} + +/// Discovery that calls the project's discover functions with a target's providers. +#[derive(Clone, Debug)] +pub struct LiveDiscovery { + /// The target whose providers the functions get; `None` for the project's default target. + pub target: Option, + /// The sets from before, reused where `rediscover` leaves a set out and kept when one fails. + pub previous: DiscoveredSets, + pub rediscover: Rediscover, + /// Whether a failed set keeps its last good result, as a location does; otherwise the compile fails. + pub keep_last_good: bool, + /// The server whose current snapshot gives a failed set with no result its last good one. + pub seed: Option, +} + +/// The location's server and target; its credential is read from the environment when used. +#[derive(Clone, Debug)] +pub struct SeedSource { + pub server_url: String, + pub location_id: Uuid, + pub target: String, +} + +/// Which discover functions a live discovery calls. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Rediscover { + All, + Only(BTreeSet), +} diff --git a/crates/sqlbuild-python-front/src/discovered_sets/types.rs b/crates/sqlbuild-python-front/src/discovered_sets/types.rs new file mode 100644 index 0000000000..017517eccb --- /dev/null +++ b/crates/sqlbuild-python-front/src/discovered_sets/types.rs @@ -0,0 +1,10 @@ +//! The registered function that calls one discover function. + +use pyo3::prelude::{Bound, PyAny, Python}; + +/// Calls a discover function: `(project dir, target)`, `(record, for_each functions)`; JSON or why not. +pub type DiscoverRunner = for<'py> fn( + Python<'py>, + (&Bound<'py, PyAny>, Option<&str>), + (&Bound<'py, PyAny>, &Bound<'py, PyAny>), +) -> Result; diff --git a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs index 0387d10c0e..1b9a98dc24 100644 --- a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs +++ b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_providers.rs @@ -14,9 +14,12 @@ use sqlbuild_host::entries::models::UserCodeHost; use crate::discovery::_helpers::python_files::imported_modules::{ ProjectDir, discovered, discovery_error, discovery_error_from, module_functions, shim, tuple_of, }; +use crate::discovery::_helpers::sources::provider_secrets::INVOCATION_TAKES_ALLOW_FLAG; use crate::discovery::_helpers::sources::provider_secrets::TARGET_ALLOWED_MISSING_SECRETS; use crate::discovery::constants::ALLOW_MISSING_SECRETS_FLAG; use crate::discovery::models::SecretPolicy; +use sqlbuild_core::process_environment::main::env_file_shown::env_file_shown; +use sqlbuild_core::process_environment::main::shell_secret_fix::shell_secret_fix; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::boundary::main::imported::imported; use sqlbuild_python_base::compile_context::main::input_reads::record_settings_class_read::record_settings_class_read; @@ -155,10 +158,13 @@ fn provider_instance<'py>( relative_path.str()? ), ); - error.value(py).setattr( - "help", - format!("set {variables}, or pass {ALLOW_MISSING_SECRETS_FLAG} where secrets aren't available"), - )?; + let mut help: String = shell_secret_fix(&variables, env_file_shown().as_deref()); + if INVOCATION_TAKES_ALLOW_FLAG.get() { + help.push_str(&format!( + ", or pass {ALLOW_MISSING_SECRETS_FLAG} where secrets aren't available" + )); + } + error.value(py).setattr("help", help)?; return Err(error); } Ok((provider_class.call_method0("model_construct")?, missing)) diff --git a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs index a5773846a8..45e07ed7ec 100644 --- a/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs +++ b/crates/sqlbuild-python-front/src/discovery/_helpers/python_files/imported_python_nodes.rs @@ -15,6 +15,7 @@ use crate::discovery::_helpers::python_files::imported_modules::{ module_functions, shim, tuple_of, }; use crate::discovery::_helpers::python_files::python_hook_files::discover_python_hook_files; +use sqlbuild_orchestration::discovered_sets::main::parse_check_every::parse_check_every; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::native_host::main::host_entry::host_entry; use sqlbuild_python_base::records::main::construct::new_record::new_record; @@ -26,6 +27,9 @@ const AUDIT_CASE: UserCodeHost = UserCodeHost::AuditCase; const READ_FACTORY: UserCodeHost = UserCodeHost::ReadFactoryDefinition; const READ_AUDIT_FACTORY: UserCodeHost = UserCodeHost::ReadAuditFactoryDefinition; const READ_HOOK: UserCodeHost = UserCodeHost::ReadHookDefinition; +/// The item field a node's identity leaves out: a failure message does not change what the node runs. +const DISCOVERED_ERROR_KEY: &str = "error"; +const READ_DISCOVER: UserCodeHost = UserCodeHost::ReadDiscoverDefinition; const NOT_A_NODE: &str = "that is not a SQLBuild asset, loader, or check"; /// One Python-node kind: its reader, record class, bucket and copied definition fields. @@ -70,6 +74,7 @@ const NODE_KINDS: [NodeKind; 3] = [ "columns", "column_lineage", "retry", + "for_each", ], }, NodeKind { @@ -88,12 +93,18 @@ const NODE_KINDS: [NodeKind; 3] = [ }, ]; -/// Discovered loaders, assets, checks and audit factories, in discovery order. +/// Discovered Python nodes, discover functions, `for_each` assets and audit factories, in order. pub(crate) struct Buckets<'py> { - pub(crate) nodes: [Vec>; 3], + /// Loaders, assets, checks, discover functions and `for_each` assets. + pub(crate) nodes: [Vec>; 5], pub(crate) audit_factories: Vec<(String, String, Bound<'py, PyAny>)>, } +/// The `Buckets::nodes` slot of `@discover` functions. +pub(crate) const DISCOVER_BUCKET: usize = 3; +/// The `Buckets::nodes` slot of assets that run once per discovered item. +pub(crate) const FOR_EACH_BUCKET: usize = 4; + /// The module and the file it was imported from. struct ImportedModule<'py> { file_path: Bound<'py, PyAny>, @@ -109,6 +120,11 @@ impl<'py> Buckets<'py> { providers: &Bound<'py, PyDict>, ) -> PyResult { let py: Python<'py> = project.py(); + if let Some(read) = definition(function, READ_DISCOVER)? { + let record = discover_function(project, (file_path, function), (&read, providers))?; + self.nodes[DISCOVER_BUCKET].push(record); + return Ok(true); + } for kind in &NODE_KINDS { let Some(read) = definition(function, kind.reader)? else { continue; @@ -130,8 +146,14 @@ impl<'py> Buckets<'py> { } }; let identity: Bound<'py, PyAny> = node_identity(py, kind.identity, &get)?; + let for_each: bool = !get("for_each")?.is_none(); pairs.push(("identity", identity)); - self.nodes[kind.bucket].push(discovered(py, kind.record, &pairs)?); + let record: Bound<'py, PyAny> = discovered(py, kind.record, &pairs)?; + if !for_each { + self.nodes[kind.bucket].push(record); + } else { + self.nodes[FOR_EACH_BUCKET].push(record); + } return Ok(true); } Ok(false) @@ -264,6 +286,41 @@ impl<'py> Buckets<'py> { } } +/// The record of one `@discover` function, its `check_every` read as seconds. +fn discover_function<'py>( + project: &ProjectDir<'py>, + (file_path, function): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), + (read, providers): (&Bound<'py, PyAny>, &Bound<'py, PyDict>), +) -> PyResult> { + let py: Python<'py> = project.py(); + let name: Bound<'py, PyAny> = native_field(read, "name")?; + let check_every: Option = native_field(read, "check_every")?.extract()?; + let seconds: Option = check_every + .map(|text| { + parse_check_every(&text).map_err(|problem| { + let location = project.relative_to(file_path).unwrap_or_default(); + discovery_error( + py, + NODE_ERROR, + format!("Discover function '{name}' in {location}: {problem}"), + ) + }) + }) + .transpose()?; + discovered( + py, + RecordId::DiscoveredDiscoverFunction, + &[ + ("file_path", file_path.clone()), + ("relative_path", project.relative(file_path)?), + ("name", name.clone()), + ("function", function.clone()), + ("check_every_seconds", seconds.into_bound_py_any(py)?), + ("provider_usages", provider_usages(function, providers)?), + ], + ) +} + /// The Python-node kinds an audit factory is also decorated as. fn node_definition_names(function: &Bound<'_, PyAny>) -> PyResult> { let mut names: Vec<&'static str> = Vec::new(); @@ -468,6 +525,16 @@ fn decorator_config<'py>( "ASSET" => { config.set_item("columns", get("columns")?)?; config.set_item("column_lineage", get("column_lineage")?)?; + let discovered: Bound<'py, PyAny> = get("discovered")?; + if let Ok(discovered) = discovered.cast::() { + let identifying: Bound<'py, PyDict> = PyDict::new(py); + for (key, value) in discovered.iter() { + if key.extract::()? != DISCOVERED_ERROR_KEY { + identifying.set_item(key, value)?; + } + } + config.set_item("discovered", identifying)?; + } } "CHECK" => { config.set_item("severity", get("severity")?.getattr("value")?)?; diff --git a/crates/sqlbuild-python-front/src/discovery/_helpers/sources/provider_secrets.rs b/crates/sqlbuild-python-front/src/discovery/_helpers/sources/provider_secrets.rs index da986a3f51..87befa8281 100644 --- a/crates/sqlbuild-python-front/src/discovery/_helpers/sources/provider_secrets.rs +++ b/crates/sqlbuild-python-front/src/discovery/_helpers/sources/provider_secrets.rs @@ -5,6 +5,8 @@ use std::cell::{Cell, RefCell}; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use crate::discovery::main::sources::secret_places::secret_places; +use sqlbuild_core::process_environment::main::env_file_shown::env_file_shown; +use sqlbuild_core::process_environment::main::shell_secret_fix::shell_secret_fix; use sqlbuild_python_base::orchestration_reads::main::missing_secrets::missing_secrets; use sqlbuild_python_base::records::main::construct::new_annotated_error::new_annotated_error; use sqlbuild_python_base::records::main::fields::field::field; @@ -16,6 +18,8 @@ pub(crate) const SINK_COLLECTIONS: [&str; 2] = ["event_exporters", "command_outp thread_local! { /// Whether the invocation running on this thread passed `--allow-missing-secrets`. pub(crate) static INVOCATION_ALLOWS_MISSING_SECRETS: Cell = const { Cell::new(false) }; + /// Whether the command running on this thread takes `--allow-missing-secrets`. + pub(crate) static INVOCATION_TAKES_ALLOW_FLAG: Cell = const { Cell::new(false) }; /// The `--target` of the invocation running on this thread. pub(crate) static INVOCATION_TARGET: RefCell> = const { RefCell::new(None) }; /// The target, and the providers its `allow_missing_secrets` lists, for the discovery running on this thread. @@ -89,8 +93,10 @@ pub(crate) fn require_used_secrets( ), &[( "help", - "set each variable in this shell or the project's env file, or narrow the selection" - .to_owned(), + format!( + "{}, or narrow the selection", + shell_secret_fix("each variable", env_file_shown().as_deref()) + ), )], )) } diff --git a/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_python_node_functions.rs b/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_python_node_functions.rs index 21b42a7f18..31a8cbe5fe 100644 --- a/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_python_node_functions.rs +++ b/crates/sqlbuild-python-front/src/discovery/main/python_files/discover_python_node_functions.rs @@ -28,7 +28,7 @@ pub fn discover_python_node_functions<'py>( None => PyDict::new(py), }; let mut buckets = Buckets { - nodes: [Vec::new(), Vec::new(), Vec::new()], + nodes: [Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()], audit_factories: Vec::new(), }; let node_root: Bound<'py, PyAny> = project.child(PYTHON_NODE_ROOT)?; @@ -48,7 +48,7 @@ pub fn discover_python_node_functions<'py>( )?; discovered_nodes?; } - let [loaders, assets, checks] = buckets.nodes; + let [loaders, assets, checks, discover_functions, for_each_assets] = buckets.nodes; discovered( py, RecordId::DiscoveredPythonNodeFunctions, @@ -56,6 +56,8 @@ pub fn discover_python_node_functions<'py>( ("loaders", tuple_of(py, loaders)?), ("assets", tuple_of(py, assets)?), ("checks", tuple_of(py, checks)?), + ("discover_functions", tuple_of(py, discover_functions)?), + ("for_each_assets", tuple_of(py, for_each_assets)?), ( "audit_factories", tuple_of( diff --git a/crates/sqlbuild-python-front/src/discovery/models.rs b/crates/sqlbuild-python-front/src/discovery/models.rs index 86b3aa6448..1e79056211 100644 --- a/crates/sqlbuild-python-front/src/discovery/models.rs +++ b/crates/sqlbuild-python-front/src/discovery/models.rs @@ -7,7 +7,8 @@ use crate::discovery::_helpers::records::model_file_record::Locations; use crate::discovery::_helpers::records::model_file_record::ModelFileFields; use crate::discovery::_helpers::records::model_file_record::ModelFilePaths; use crate::discovery::_helpers::sources::provider_secrets::{ - INVOCATION_ALLOWS_MISSING_SECRETS, INVOCATION_TARGET, TARGET_ALLOWED_MISSING_SECRETS, + INVOCATION_ALLOWS_MISSING_SECRETS, INVOCATION_TAKES_ALLOW_FLAG, INVOCATION_TARGET, + TARGET_ALLOWED_MISSING_SECRETS, }; use crate::discovery::main::records::projected_text::projected_text; use pyo3::FromPyObject; @@ -334,17 +335,18 @@ pub struct NodeRow { pub(crate) depends_on: Vec, } -/// `--allow-missing-secrets` and `--target` for one invocation, restored when the invocation ends. +/// `--allow-missing-secrets`, whether the command takes it, and `--target` for one invocation, restored when the invocation ends. #[derive(Debug)] pub struct MissingSecretsScope { - pub(crate) previous: (bool, Option), + pub(crate) previous: (bool, bool, Option), } impl MissingSecretsScope { - pub fn enter(allowed: bool, target: Option) -> Self { + pub fn enter((allowed, takes_flag): (bool, bool), target: Option) -> Self { Self { previous: ( INVOCATION_ALLOWS_MISSING_SECRETS.replace(allowed), + INVOCATION_TAKES_ALLOW_FLAG.replace(takes_flag), INVOCATION_TARGET.replace(target), ), } @@ -354,7 +356,8 @@ impl MissingSecretsScope { impl Drop for MissingSecretsScope { fn drop(&mut self) { INVOCATION_ALLOWS_MISSING_SECRETS.set(self.previous.0); - INVOCATION_TARGET.replace(self.previous.1.take()); + INVOCATION_TAKES_ALLOW_FLAG.set(self.previous.1); + INVOCATION_TARGET.replace(self.previous.2.take()); } } diff --git a/crates/sqlbuild-python-front/src/lib.rs b/crates/sqlbuild-python-front/src/lib.rs index 6393f84a48..3a9400e545 100644 --- a/crates/sqlbuild-python-front/src/lib.rs +++ b/crates/sqlbuild-python-front/src/lib.rs @@ -10,6 +10,7 @@ pub mod compile_driver; pub mod contracts; pub mod cost_context; pub mod cursor; +pub mod discovered_sets; pub mod discovery; pub mod execution_history; pub mod macro_bridge; diff --git a/crates/sqlbuild-python-front/src/render/_helpers/calls/macro_calls.rs b/crates/sqlbuild-python-front/src/render/_helpers/calls/macro_calls.rs index 584ff42afd..8ed4c6d3bc 100644 --- a/crates/sqlbuild-python-front/src/render/_helpers/calls/macro_calls.rs +++ b/crates/sqlbuild-python-front/src/render/_helpers/calls/macro_calls.rs @@ -60,7 +60,7 @@ pub(crate) fn splice_macro_calls( outputs: Vec, ) -> PyResult<(String, Vec)> { let spliced = py - .compiler_detach(|| Ok(splice_calls(sql, &sites, &outputs))) + .compiler_detach(|| Ok(splice_calls(sql, &sites, &outputs, None))) .map_err(compiler_error)?; let (rendered, spans) = spliced.ok_or_else(|| PyValueError::new_err("macro call sites do not fit the SQL"))?; diff --git a/crates/sqlbuild-python-front/src/render/_helpers/declarations/declaration_expansion.rs b/crates/sqlbuild-python-front/src/render/_helpers/declarations/declaration_expansion.rs index aab5b52137..03e00d2b02 100644 --- a/crates/sqlbuild-python-front/src/render/_helpers/declarations/declaration_expansion.rs +++ b/crates/sqlbuild-python-front/src/render/_helpers/declarations/declaration_expansion.rs @@ -13,6 +13,8 @@ use sqlbuild_analysis::compiled_project::models::{ DeclarationSplice, InaccessibleDeclaration, SplicedSql, }; use sqlbuild_analysis::sql_macros::models::{ExpandedText, TypedCall}; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; use crate::render::_helpers::sql_macros::sql_macro_host::{ expanded_sql_macro_calls, is_sql_macro_reference, reject_bare_macro_calls, @@ -114,6 +116,19 @@ pub(crate) fn expand_declarations<'py>( if let Some(code) = request.stop { return Err(compile_error(request, &DeclarationError::ScanStop(code))); } + let syntax: Option<&LexicalSyntax> = request.sql_macros.and_then(|source| source.syntax); + let (splices, leads) = bound_splices(request.sql, splices, syntax); + for (index, lead) in leads { + for (_, calls) in call_splices + .iter_mut() + .filter(|(splice, _)| *splice == index) + { + for call in calls { + call.start += lead; + call.end += lead; + } + } + } let spliced: SplicedSql = splice_declarations(request.sql, &splices); let typed_calls: Vec = spliced_call_positions(&spliced, call_splices); Ok(ExpandedDeclarations { @@ -125,6 +140,43 @@ pub(crate) fn expand_declarations<'py>( }) } +/// Bound each character-indexed replacement against comments, returning how far each changed one moved. +fn bound_splices( + sql: &str, + mut splices: Vec, + syntax: Option<&LexicalSyntax>, +) -> (Vec, Vec<(usize, usize)>) { + if splices.is_empty() { + return (splices, Vec::new()); + } + let characters: Vec = if sql.is_ascii() { + Vec::new() + } else { + sql.char_indices() + .map(|(offset, _)| offset) + .chain([sql.len()]) + .collect() + }; + let byte = |position: usize| characters.get(position).copied().unwrap_or(position); + let expansions: Vec<(usize, usize, &str)> = splices + .iter() + .map(|splice| { + ( + byte(splice.start), + byte(splice.end), + splice.replacement.as_str(), + ) + }) + .collect(); + let bounded = bounded_expansions(sql, &expansions, syntax); + let mut leads: Vec<(usize, usize)> = Vec::with_capacity(bounded.len()); + for expansion in bounded { + splices[expansion.index].replacement = expansion.text; + leads.push((expansion.index, expansion.lead)); + } + (splices, leads) +} + /// Each call text's typed calls moved to where its splice landed in `spliced`, by byte. fn spliced_call_positions( spliced: &SplicedSql, diff --git a/crates/sqlbuild-python-front/src/render/_helpers/expansion/macro_expansion.rs b/crates/sqlbuild-python-front/src/render/_helpers/expansion/macro_expansion.rs index 635ac44139..a4f46aaf7c 100644 --- a/crates/sqlbuild-python-front/src/render/_helpers/expansion/macro_expansion.rs +++ b/crates/sqlbuild-python-front/src/render/_helpers/expansion/macro_expansion.rs @@ -144,7 +144,7 @@ pub(crate) fn expanded<'py>( .iter() .map(|site| (site.start, site.end)) .collect(); - let (rendered, spans) = splice_calls(text.text, &bounds, &outputs) + let (rendered, spans) = splice_calls(text.text, &bounds, &outputs, this.syntax.as_ref()) .ok_or_else(|| PyValueError::new_err("macro call sites do not fit the SQL"))?; let facts = this.facts.borrow(); Ok(ExpansionOutput { diff --git a/crates/sqlbuild-python-output/src/build_progress/_helpers/build_callbacks.rs b/crates/sqlbuild-python-output/src/build_progress/_helpers/build_callbacks.rs index e867be97e1..c04c1ff3e0 100644 --- a/crates/sqlbuild-python-output/src/build_progress/_helpers/build_callbacks.rs +++ b/crates/sqlbuild-python-output/src/build_progress/_helpers/build_callbacks.rs @@ -3,6 +3,9 @@ use std::collections::HashMap; use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult}; +use pyo3::types::{PyCFunction, PyDict, PyTuple}; + +use crate::build_progress::models::BuildProgressCallbacks; use sqlbuild_core::build_progress::models::{SchedulerStateText, StatementText, TestResultText}; use crate::build_progress::_helpers::result_text::optional; @@ -107,6 +110,8 @@ pub(crate) struct CallbackState { pub(crate) query_counts: HashMap, pub(crate) query_omitted: usize, pub(crate) last_query: Option, + /// Long-running nodes for the heartbeat line of captured output. + pub(crate) heartbeat: crate::build_progress::_helpers::heartbeat::HeartbeatState, } pub(crate) fn scheduler_state(state: &Bound<'_, PyAny>) -> PyResult { @@ -129,3 +134,21 @@ pub(crate) fn statement(telemetry: &Bound<'_, PyAny>) -> PyResult phase: text(telemetry, "phase")?, }) } + +/// What a relay does with its owner and the arguments it was called with. +pub(crate) type Forward = fn(&BuildProgressCallbacks, &Bound<'_, PyTuple>) -> PyResult<()>; + +/// A callable that calls `forward` on `callbacks`, built without a Python lookup. +pub(crate) fn relay<'py>( + callbacks: &Bound<'py, PyAny>, + forward: Forward, +) -> PyResult> { + let owned: Py = callbacks + .downcast::()? + .clone() + .unbind(); + let call = move |arguments: &Bound<'_, PyTuple>, + _keywords: Option<&Bound<'_, PyDict>>| + -> PyResult<()> { forward(owned.get(), arguments) }; + Ok(PyCFunction::new_closure(callbacks.py(), None, None, call)?.into_any()) +} diff --git a/crates/sqlbuild-python-output/src/build_progress/_helpers/heartbeat.rs b/crates/sqlbuild-python-output/src/build_progress/_helpers/heartbeat.rs new file mode 100644 index 0000000000..3c023d0a8c --- /dev/null +++ b/crates/sqlbuild-python-output/src/build_progress/_helpers/heartbeat.rs @@ -0,0 +1,132 @@ +//! While output is captured rather than shown on a terminal, one line names the nodes that run long. + +use std::collections::BTreeMap; +use std::sync::mpsc::{self, RecvTimeoutError, Sender}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use pyo3::prelude::{Bound, Py, Python}; +use sqlbuild_core::build_progress::main::heartbeat_interval::heartbeat_interval; +use sqlbuild_core::build_progress::main::heartbeat_message::heartbeat_message; +use sqlbuild_core::build_progress::models::RunningNodeText; +use sqlbuild_core::cli_text::models::CliStyle; + +use crate::build_progress::models::BuildProgressCallbacks; + +const HEARTBEAT_TICK: Duration = Duration::from_secs(1); + +/// A running node's start and the rows it has written, unknown once a batch reports no count. +#[derive(Debug)] +pub(crate) struct RunningNode { + pub(crate) started: Instant, + pub(crate) rows: Option, + pub(crate) uncounted: bool, +} + +/// The running nodes, how many heartbeats this long stretch has printed, and the timer thread. +#[derive(Debug, Default)] +pub(crate) struct HeartbeatState { + pub(crate) running: BTreeMap, + pub(crate) beats: usize, + pub(crate) last: Option, + pub(crate) stop: Option>, + pub(crate) thread: Option>, +} + +impl HeartbeatState { + /// The heartbeat line when one is due: once a node has run 30 s, then backing off; a quiet stretch starts over. + pub(crate) fn due_line(&mut self, now: Instant, style: CliStyle) -> Option { + let running: Vec = self + .running + .iter() + .map(|(name, node)| RunningNodeText { + name: name.clone(), + elapsed_seconds: now.duration_since(node.started).as_secs(), + rows_so_far: node.rows, + }) + .collect(); + let longest: u64 = running + .iter() + .map(|node| node.elapsed_seconds) + .max() + .unwrap_or_default(); + if Duration::from_secs(longest) < heartbeat_interval(0) { + self.beats = 0; + self.last = None; + return None; + } + let due: bool = self + .last + .is_none_or(|last| now.duration_since(last) >= heartbeat_interval(self.beats)); + if !due { + return None; + } + self.beats += 1; + self.last = Some(now); + Some(heartbeat_message(&running, style)) + } +} + +/// Record a started node and start the timer thread on the first one. +pub(crate) fn node_started(callbacks: &Bound<'_, BuildProgressCallbacks>, name: &str) { + let owner: &BuildProgressCallbacks = callbacks.get(); + let mut state = owner.state(); + state.heartbeat.running.insert( + name.to_owned(), + RunningNode { + started: Instant::now(), + rows: None, + uncounted: false, + }, + ); + if state.heartbeat.thread.is_some() { + return; + } + let (stop, stopped) = mpsc::channel::<()>(); + let owned: Py = callbacks.clone().unbind(); + state.heartbeat.stop = Some(stop); + state.heartbeat.thread = Some(std::thread::spawn(move || { + while stopped.recv_timeout(HEARTBEAT_TICK) == Err(RecvTimeoutError::Timeout) { + let owner: &BuildProgressCallbacks = owned.get(); + let line: Option = owner + .state() + .heartbeat + .due_line(Instant::now(), owner.style); + if let Some(line) = line { + let _ = Python::attach(|py| owner.write_persistent(py, &line)); + } + } + })); +} + +/// Add a finished batch's rows to a running node; a batch with no count leaves its rows unknown. +pub(crate) fn batch_rows(owner: &BuildProgressCallbacks, name: &str, rows: Option) { + let mut state = owner.state(); + let Some(node) = state.heartbeat.running.get_mut(name) else { + return; + }; + node.uncounted |= rows.is_none(); + node.rows = match (node.uncounted, rows) { + (false, Some(rows)) => Some(node.rows.unwrap_or_default() + rows), + _ => None, + }; +} + +/// Set a running loader's rows written so far. +pub(crate) fn rows_written(owner: &BuildProgressCallbacks, name: &str, rows: i64) { + if let Some(node) = owner.state().heartbeat.running.get_mut(name) { + node.rows = Some(rows); + } +} + +/// Stop the timer thread and wait for it, without holding the interpreter it may be writing through. +pub(crate) fn stop(py: Python<'_>, owner: &BuildProgressCallbacks) { + let (stop, thread) = { + let mut state = owner.state(); + (state.heartbeat.stop.take(), state.heartbeat.thread.take()) + }; + drop(stop); + if let Some(thread) = thread { + let _ = py.detach(|| thread.join()); + } +} diff --git a/crates/sqlbuild-python-output/src/build_progress/_helpers/mod.rs b/crates/sqlbuild-python-output/src/build_progress/_helpers/mod.rs index 7208cda47c..15089f2796 100644 --- a/crates/sqlbuild-python-output/src/build_progress/_helpers/mod.rs +++ b/crates/sqlbuild-python-output/src/build_progress/_helpers/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod audit_progress; pub(crate) mod build_callbacks; pub(crate) mod footer; pub(crate) mod getters; +pub(crate) mod heartbeat; pub(crate) mod nested_progress; pub(crate) mod plan_facts; pub(crate) mod progress_reporters; diff --git a/crates/sqlbuild-python-output/src/build_progress/_helpers/result_text.rs b/crates/sqlbuild-python-output/src/build_progress/_helpers/result_text.rs index 969cee0698..58cffb4e3a 100644 --- a/crates/sqlbuild-python-output/src/build_progress/_helpers/result_text.rs +++ b/crates/sqlbuild-python-output/src/build_progress/_helpers/result_text.rs @@ -22,7 +22,7 @@ use sqlbuild_core::test_command::models::TestParameter; use sqlbuild_host::models::{ AuditEvaluationMode, AuditExecutionResult, BuildExecutionResult, ExecutionStatus, FunctionExecutionResult, HookExecutionResult, HookPhase, LifeCycleEvent, LifeCycleEventKind, - LoadExecutionResult, MeasuredValue, ModelExecutionResult, SeedExecutionResult, + LoadExecutionResult, LogLevel, MeasuredValue, ModelExecutionResult, SeedExecutionResult, SqlTestExecutionResult, StepResult, }; use sqlbuild_host::types::ResultEnum; @@ -67,7 +67,12 @@ fn events(value: &[LifeCycleEvent]) -> Vec { .iter() .map(|event| match event.kind { LifeCycleEventKind::Sql => LifecycleEventText::Sql(event.content.clone()), - LifeCycleEventKind::Log => LifecycleEventText::Log(event.content.clone()), + LifeCycleEventKind::Log => LifecycleEventText::Log(match event.level { + Some(level @ (LogLevel::Warning | LogLevel::Error)) => { + format!("{}: {}", level.value(), event.content) + } + _ => event.content.clone(), + }), }) .collect() } diff --git a/crates/sqlbuild-python-output/src/build_progress/main/batch_complete_callback.rs b/crates/sqlbuild-python-output/src/build_progress/main/batch_complete_callback.rs index 2ed7aef08c..dd17d5ac0a 100644 --- a/crates/sqlbuild-python-output/src/build_progress/main/batch_complete_callback.rs +++ b/crates/sqlbuild-python-output/src/build_progress/main/batch_complete_callback.rs @@ -1,21 +1,12 @@ //! A callable that forwards each completed microbatch to `callbacks`, built without a Python lookup. -use crate::build_progress::models::BuildProgressCallbacks; -use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult}; -use pyo3::types::{PyCFunction, PyDict, PyTuple, PyTupleMethods}; +use crate::build_progress::_helpers::build_callbacks::relay; +use pyo3::prelude::{Bound, PyAny, PyResult}; +use pyo3::types::PyTupleMethods; /// A callable that forwards each completed microbatch to `callbacks`, built without a Python lookup. pub fn batch_complete_callback<'py>(callbacks: &Bound<'py, PyAny>) -> PyResult> { - let owned: Py = callbacks - .downcast::()? - .clone() - .unbind(); - let forward = move |arguments: &Bound<'_, PyTuple>, - _keywords: Option<&Bound<'_, PyDict>>| - -> PyResult<()> { - owned - .get() - .write_batch_complete(arguments.py(), &arguments.get_item(0)?) - }; - Ok(PyCFunction::new_closure(callbacks.py(), None, None, forward)?.into_any()) + relay(callbacks, |owner, arguments| { + owner.on_batch_complete(arguments.py(), &arguments.get_item(0)?) + }) } diff --git a/crates/sqlbuild-python-output/src/build_progress/main/check_callback.rs b/crates/sqlbuild-python-output/src/build_progress/main/check_callback.rs index 22b078cd90..03f5d47bab 100644 --- a/crates/sqlbuild-python-output/src/build_progress/main/check_callback.rs +++ b/crates/sqlbuild-python-output/src/build_progress/main/check_callback.rs @@ -1,27 +1,20 @@ //! Forward a Python check lifecycle callback directly to its native progress owner. -use crate::build_progress::models::BuildProgressCallbacks; -use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult}; -use pyo3::types::{PyCFunction, PyDict, PyTuple, PyTupleMethods}; +use crate::build_progress::_helpers::build_callbacks::relay; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use pyo3::types::PyTupleMethods; /// Forward a Python check lifecycle callback directly to its native progress owner. pub fn check_callback<'py>( callbacks: &Bound<'py, PyAny>, completion: bool, ) -> PyResult> { - let owned: Py = callbacks - .downcast::()? - .clone() - .unbind(); - let forward = move |arguments: &Bound<'_, PyTuple>, - _keywords: Option<&Bound<'_, PyDict>>| - -> PyResult<()> { - let value = arguments.get_item(0)?; - if completion { - owned.get().on_check_complete(arguments.py(), &value) - } else { - owned.get().on_check_start(arguments.py(), value.extract()?) - } - }; - Ok(PyCFunction::new_closure(callbacks.py(), None, None, forward)?.into_any()) + if completion { + return relay(callbacks, |owner, arguments| { + owner.on_check_complete(arguments.py(), &arguments.get_item(0)?) + }); + } + relay(callbacks, |owner, arguments| { + owner.on_check_start(arguments.py(), arguments.get_item(0)?.extract()?) + }) } diff --git a/crates/sqlbuild-python-output/src/build_progress/main/mod.rs b/crates/sqlbuild-python-output/src/build_progress/main/mod.rs index 984863b034..e571014c65 100644 --- a/crates/sqlbuild-python-output/src/build_progress/main/mod.rs +++ b/crates/sqlbuild-python-output/src/build_progress/main/mod.rs @@ -12,6 +12,7 @@ pub mod register_nested_progress; pub mod register_progress_reporters; pub mod register_progress_text; pub mod report_build_checks; +pub mod rows_written_callback; pub mod test_label; pub mod test_result_label; pub mod with_verbose_inspection; diff --git a/crates/sqlbuild-python-output/src/build_progress/main/rows_written_callback.rs b/crates/sqlbuild-python-output/src/build_progress/main/rows_written_callback.rs new file mode 100644 index 0000000000..f991bdd2a1 --- /dev/null +++ b/crates/sqlbuild-python-output/src/build_progress/main/rows_written_callback.rs @@ -0,0 +1,13 @@ +//! A callable that forwards a running loader's rows so far to `callbacks`, built without a Python lookup. + +use crate::build_progress::_helpers::build_callbacks::relay; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use pyo3::types::PyTupleMethods; + +/// A callable taking a node key and its rows so far, which a worker reports as the node's progress. +pub fn rows_written_callback<'py>(callbacks: &Bound<'py, PyAny>) -> PyResult> { + relay(callbacks, |owner, arguments| { + let key: String = arguments.get_item(0)?.extract()?; + owner.on_rows_written(arguments.py(), &key, arguments.get_item(1)?.extract()?) + }) +} diff --git a/crates/sqlbuild-python-output/src/build_progress/models.rs b/crates/sqlbuild-python-output/src/build_progress/models.rs index c7140246bf..321def81b7 100644 --- a/crates/sqlbuild-python-output/src/build_progress/models.rs +++ b/crates/sqlbuild-python-output/src/build_progress/models.rs @@ -11,6 +11,7 @@ use crate::build_progress::_helpers::build_callbacks::resource_identity; use crate::build_progress::_helpers::build_callbacks::result_kind; use crate::build_progress::_helpers::build_callbacks::scheduler_state; use crate::build_progress::_helpers::build_callbacks::statement; +use crate::build_progress::_helpers::heartbeat; use crate::build_progress::_helpers::nested_progress::ITEM_OPTIONS; use crate::build_progress::_helpers::nested_progress::MIN_NAME_WIDTH; use crate::build_progress::_helpers::nested_progress::child_rows; @@ -707,6 +708,9 @@ impl BuildProgressCallbacks { if let Some(worker) = &callbacks.worker { worker.start(py, &name, resource_kind)?; } + if !callbacks.is_tty { + heartbeat::node_started(slf, &name); + } if let Some(projector) = &callbacks.projector { let options: Bound<'_, PyDict> = PyDict::new(py); options.set_item("resource_name", name)?; @@ -750,15 +754,34 @@ impl BuildProgressCallbacks { Ok(()) } - /// Keep a line per completed microbatch when no live spinner row shows batch progress. + /// Keep a line per completed microbatch when no live spinner row shows batch progress; a worker reports the rows so far. pub(crate) fn on_batch_complete( &self, py: Python<'_>, progress: &Bound<'_, PyAny>, ) -> PyResult<()> { + let name: String = text(progress, "model_name")?; + let rows: Option = native_field(progress, "rows_affected")?.extract()?; + if let Some(worker) = &self.worker { + worker.batch_rows(py, &format!("model:{name}"), rows)?; + } + heartbeat::batch_rows(self, &name, rows); self.write_batch_complete(py, progress) } + /// A worker reports the rows a running loader has written so far. + pub(crate) fn on_rows_written(&self, py: Python<'_>, key: &str, rows: i64) -> PyResult<()> { + heartbeat::rows_written( + self, + key.split_once(':').map_or(key, |(_, name)| name), + rows, + ); + match &self.worker { + Some(worker) => worker.rows_written(py, key, rows), + None => Ok(()), + } + } + /// Report one deduplicated concurrent scheduler state transition. pub(crate) fn on_scheduler_state( &self, @@ -817,10 +840,14 @@ impl BuildProgressCallbacks { ) -> PyResult<()> { let py: Python<'_> = slf.py(); let callbacks: &Self = slf.get(); + let identity: Option<(String, String)> = resource_identity(node_result)?; + if let Some((name, _)) = &identity { + callbacks.state().heartbeat.running.remove(name); + } if let Some(worker) = &callbacks.worker - && let Some((_, key)) = resource_identity(node_result)? + && let Some((_, key)) = &identity { - worker.completed(node_result, &key)?; + worker.completed(node_result, key)?; } let kind: ResultKind = result_kind(node_result)?; let mut result: Bound<'_, PyAny> = node_result.clone(); @@ -872,8 +899,9 @@ impl BuildProgressCallbacks { self.write_event(py, result) } - /// Close the optional structured execution event stream. - pub(crate) fn close(&self, py: Python<'_>) -> PyResult<()> { + /// Stop the heartbeat and close the optional structured execution event stream. + pub fn close(&self, py: Python<'_>) -> PyResult<()> { + heartbeat::stop(py, self); let (scheduler, query) = { let state = self.state(); ( diff --git a/crates/sqlbuild-python-output/src/compute_logs/_helpers/storage.rs b/crates/sqlbuild-python-output/src/compute_logs/_helpers/storage.rs index 939ff34709..8346ed3cc7 100644 --- a/crates/sqlbuild-python-output/src/compute_logs/_helpers/storage.rs +++ b/crates/sqlbuild-python-output/src/compute_logs/_helpers/storage.rs @@ -38,9 +38,13 @@ use crate::compute_logs::_helpers::conversion::metadata_model; use crate::compute_logs::_helpers::conversion::rejection; use crate::compute_logs::_helpers::conversion::storage_error; use crate::compute_logs::_helpers::conversion::stream_index; +use crate::recall::constants::STDOUT_STREAM_INDEX; use crate::recall::main::forward_diagnostic::forward_diagnostic; use crate::recall::main::forward_output::forward_output; use crate::recall::models::RecallLifecycleSink; +use sqlbuild_orchestration::run_output::main::forward_output::forward_output as forward_run_output; +use sqlbuild_orchestration::run_output::main::wait_for_output_room::wait_for_output_room; +use sqlbuild_orchestration::run_output::models::OutputStream; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::boundary::main::imported::imported; use sqlbuild_python_base::boundary::models::KeywordArguments; @@ -127,14 +131,26 @@ impl LocalFilesystemComputeLogStorage { }; writers[stream].write_all(data)?; self.forward_to_recall(invocation_id, stream, data); + drop(state); + if stream != DIAGNOSTICS_STREAM { + py.detach(wait_for_output_room); + } Ok(()) } - /// Hand bytes the capture just accepted to Recall while its lock is held, so both keep one order. + /// Hand bytes the capture just accepted to Recall and the run output while its lock is held, so all keep one order. fn forward_to_recall(&self, invocation_id: &str, stream: usize, data: &[u8]) { let session = self.recall.get().map(Arc::as_ref); if stream != DIAGNOSTICS_STREAM { forward_output(session, invocation_id, (stream, data)); + forward_run_output( + if stream == STDOUT_STREAM_INDEX { + OutputStream::Stdout + } else { + OutputStream::Stderr + }, + data, + ); return; } if let Ok(line) = std::str::from_utf8(data) { diff --git a/crates/sqlbuild-python-output/src/output_capture/_helpers/context.rs b/crates/sqlbuild-python-output/src/output_capture/_helpers/context.rs index 5c27f98b91..374720431a 100644 --- a/crates/sqlbuild-python-output/src/output_capture/_helpers/context.rs +++ b/crates/sqlbuild-python-output/src/output_capture/_helpers/context.rs @@ -9,6 +9,7 @@ use pyo3::prelude::{ use pyo3::sync::PyOnceLock; use pyo3::types::PyTuple; use sqlbuild_host::entries::models::ExecutorHost; +use sqlbuild_orchestration::run_output::main::enter_output_node::enter_output_node; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::boundary::main::context_variable::context_variable; @@ -80,3 +81,44 @@ pub(crate) fn current_context(py: Python<'_>) -> PyResult> { pub(crate) fn current_output_capture_context(py: Python<'_>) -> PyResult> { current_context(py) } + +/// `with output_node_scope("model:orders"):` files what this thread prints under that node until the block ends. +#[pyclass(module = "sqlbuild._native", frozen)] +pub(crate) struct OutputNodeScope { + node_key: String, + previous: Mutex>>, +} + +#[pymethods] +impl OutputNodeScope { + fn __enter__(&self) -> PyResult<()> { + *self + .previous + .lock() + .map_err(|_| PyRuntimeError::new_err("output node scope lock is poisoned"))? = + Some(enter_output_node(Some(self.node_key.clone()))); + Ok(()) + } + + #[pyo3(signature = (*_exc_info))] + fn __exit__(&self, _exc_info: &Bound<'_, PyTuple>) -> PyResult { + let previous = self + .previous + .lock() + .map_err(|_| PyRuntimeError::new_err("output node scope lock is poisoned"))? + .take(); + if let Some(previous) = previous { + enter_output_node(previous); + } + Ok(false) + } +} + +/// A scope filing what this thread prints under `node_key`, keyed `:`. +#[pyfunction] +pub(crate) fn output_node_scope(node_key: String) -> OutputNodeScope { + OutputNodeScope { + node_key, + previous: Mutex::new(None), + } +} diff --git a/crates/sqlbuild-python-output/src/output_capture/main/register_context.rs b/crates/sqlbuild-python-output/src/output_capture/main/register_context.rs index 9c0bfedf1e..403b97da24 100644 --- a/crates/sqlbuild-python-output/src/output_capture/main/register_context.rs +++ b/crates/sqlbuild-python-output/src/output_capture/main/register_context.rs @@ -1,13 +1,17 @@ //! Register the context functions and classes. use crate::output_capture::_helpers::context::CommandOutputContext; +use crate::output_capture::_helpers::context::OutputNodeScope; use crate::output_capture::_helpers::context::command_output_context; use crate::output_capture::_helpers::context::current_output_capture_context; +use crate::output_capture::_helpers::context::output_node_scope; use pyo3::prelude::{Bound, PyModule, PyModuleMethods, PyResult, wrap_pyfunction}; /// Register the context functions and classes. pub fn register_context(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add_class::()?; + module.add_class::()?; + module.add_function(wrap_pyfunction!(output_node_scope, module)?)?; module.add_function(wrap_pyfunction!(command_output_context, module)?)?; module.add_function(wrap_pyfunction!(current_output_capture_context, module)?) } diff --git a/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/sources.rs b/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/sources.rs index 68ecae8b1c..a67aeddfbd 100644 --- a/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/sources.rs +++ b/crates/sqlbuild-python-planner/src/planner_resolution/_helpers/references/sources.rs @@ -22,6 +22,10 @@ use sqlbuild_sqltext::resolution::main::column_name_key::column_name_key; use sqlbuild_sqltext::resolution::main::{ reference_spans::reference_spans, source_alias::source_alias, }; +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; +use sqlbuild_sqltext::sql_scan::main::dialect_lexical_syntax::dialect_lexical_syntax; +use sqlbuild_sqltext::sql_scan::main::expansion_followed_by::expansion_followed_by; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; fn source_error(py: Python<'_>, message: &str, code: &str) -> PyErr { input_error(py, ErrorId::PlannerInput, message, Some(code)) @@ -333,21 +337,42 @@ pub(crate) fn resolve_sources( .is_truthy()?; let mut output = String::new(); let mut last = 0; - for span in reference_spans(sql, "source") { + let spans = reference_spans(sql, "source"); + if spans.is_empty() { + return Ok(sql.to_owned()); + } + let dialect_name: Option = dialect.syntax("sql_analysis_dialect_name")?.extract()?; + let syntax: LexicalSyntax = dialect_lexical_syntax(dialect_name.as_deref().unwrap_or_default()); + let mut relations: Vec<(usize, usize, String)> = Vec::with_capacity(spans.len()); + for span in spans { let mut relation = resolve_one( lookups, dialect, filtering, (&span.name, &sql[span.start..span.end]), )?; - output.push_str(sql.get(last..span.start).unwrap_or_default()); - last = span.end; + let mut end = span.end; if aliases && relation.trim_start().starts_with('(') { - let (end, alias) = source_alias(sql, span.end, &span.name); - relation.push_str(&format!(" AS {alias}")); - last = end; + let (aliased_end, alias) = source_alias(sql, span.end, &span.name); + let clause = format!(" AS {alias}"); + relation = expansion_followed_by(&relation, &clause, Some(&syntax)); + relation.push_str(&clause); + end = aliased_end; } - output.push_str(&relation); + relations.push((span.start, end, relation)); + } + let sites: Vec<(usize, usize, &str)> = relations + .iter() + .map(|(start, end, relation)| (*start, *end, relation.as_str())) + .collect(); + let bounded = bounded_expansions(sql, &sites, Some(&syntax)); + for expansion in bounded { + relations[expansion.index].2 = expansion.text; + } + for (start, end, relation) in &relations { + output.push_str(sql.get(last..*start).unwrap_or_default()); + output.push_str(relation); + last = *end; } output.push_str(&sql[last..]); Ok(output) diff --git a/crates/sqlbuild-python-project/src/compiled_project/constants.rs b/crates/sqlbuild-python-project/src/compiled_project/constants.rs index 9217761a3a..6858ae4f6a 100644 --- a/crates/sqlbuild-python-project/src/compiled_project/constants.rs +++ b/crates/sqlbuild-python-project/src/compiled_project/constants.rs @@ -2,10 +2,19 @@ pub const SKIP_ACTION: &str = "skip"; +/// A node's skip mode when it blocks everything downstream of it. +pub const HARD_SKIP_MODE: &str = "hard"; + pub const NO_CHANGE_REASON: &str = "no_change"; +/// Why an up-to-date node succeeded without building, as a run's node list shows it. +pub const UNCHANGED_REASON: &str = "unchanged since its last build"; + pub const REPORT_ATTEMPTS: usize = 3; +/// The shortest gap between two progress reports for one running node. +pub const PROGRESS_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10); + /// The HTTP status a control server answers while its store is busy; reports retry it. pub const STORE_BUSY_STATUS: u16 = 503; diff --git a/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_node_graph.rs b/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_node_graph.rs index 228875b32c..c0ff580357 100644 --- a/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_node_graph.rs +++ b/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_node_graph.rs @@ -177,7 +177,7 @@ fn kind_metadata<'py>( "asset", metadata( RecordId::DiscoveredPythonAssetMetadata, - &["columns", "column_lineage", "retry"], + &["columns", "column_lineage", "retry", "discovered"], )?, ), _ => ( diff --git a/crates/sqlbuild-python-project/src/native_host/main/mod.rs b/crates/sqlbuild-python-project/src/native_host/main/mod.rs index ccae65edf1..2ec2d3d7aa 100644 --- a/crates/sqlbuild-python-project/src/native_host/main/mod.rs +++ b/crates/sqlbuild-python-project/src/native_host/main/mod.rs @@ -6,3 +6,4 @@ pub mod report_synced_catalog; pub mod run_recorder; pub mod sensor_declaration; pub mod target_location; +pub mod write_stderr_line; diff --git a/crates/sqlbuild-python-project/src/native_host/main/write_stderr_line.rs b/crates/sqlbuild-python-project/src/native_host/main/write_stderr_line.rs new file mode 100644 index 0000000000..38225f1da1 --- /dev/null +++ b/crates/sqlbuild-python-project/src/native_host/main/write_stderr_line.rs @@ -0,0 +1,10 @@ +//! Write a line to Python's stderr for other domains, as the plan's own progress is written. + +use pyo3::prelude::{PyResult, Python}; + +use crate::native_host::_helpers::synced_catalog::write_stderr; + +/// `text` ends in its own newline. +pub fn write_stderr_line(py: Python<'_>, text: &str) -> PyResult<()> { + write_stderr(py, text) +} diff --git a/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/mod.rs b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/mod.rs index 1057bdb62b..cb1286bdcd 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/mod.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod snapshot_boundary; pub(crate) mod snapshot_declarations; pub(crate) mod snapshot_execution; pub(crate) mod snapshot_group_cycles; +pub(crate) mod snapshot_logs; pub(crate) mod snapshot_models; pub(crate) mod snapshot_project; pub(crate) mod snapshot_providers; diff --git a/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_execution.rs b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_execution.rs index 1e3936ef2f..1ee68e7647 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_execution.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_execution.rs @@ -1,16 +1,15 @@ //! Frozen selection, executor callbacks and completion belong to one verified worker build. use pyo3::exceptions::PyRuntimeError; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; use sqlbuild_core::models::CompiledResourceType; use sqlbuild_orchestration::runs::models::NodeOutcome; - -/// A finished node's outcome, rows affected, error code and error message. -pub(crate) type Completion = (NodeOutcome, Option, (Option, Option)); +use sqlbuild_python_base::records::main::fields::field::field; /// Failure outranks cancellation, then warnings, then success. pub(crate) fn severity(outcome: NodeOutcome) -> u8 { match outcome { - NodeOutcome::Skipped => 0, + NodeOutcome::Skipped | NodeOutcome::NotRun => 0, NodeOutcome::Success => 1, NodeOutcome::Warn => 2, NodeOutcome::Cancelled => 3, @@ -27,6 +26,13 @@ pub(crate) fn is_function(key: &str) -> bool { }) } +/// A plan key such as a `CompiledObjectKey` as its run node key, `:`. +pub(crate) fn planned_key(key: &Bound<'_, PyAny>) -> PyResult { + let kind: String = field(key, "resource_type")?.str()?.extract()?; + let name: String = field(key, "name")?.str()?.extract()?; + Ok(format!("{kind}:{name}")) +} + pub(crate) fn poisoned() -> pyo3::PyErr { PyRuntimeError::new_err("worker build outcome lock is unavailable") } diff --git a/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_logs.rs b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_logs.rs new file mode 100644 index 0000000000..f7bf86e776 --- /dev/null +++ b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_logs.rs @@ -0,0 +1,73 @@ +//! The `ctx.log` lines a finished node reports, and the note a worker leaves when run output was lost. + +use sqlbuild_host::models::{LifeCycleEvent, LifeCycleEventKind, LogLevel}; +use sqlbuild_orchestration::run_output::constants::{ + NODE_LOG_MESSAGE_BYTES, NODE_LOGS_PER_NODE, RUN_OUTPUT_NODE, +}; +use sqlbuild_orchestration::run_output::models::UploadSummary; +use sqlbuild_orchestration::runs::models::{NodeLogLevel, RunChange}; + +const ELLIPSIS: char = '\u{2026}'; + +/// Each of the node's first `ctx.log` lines with the event key it reports under; lines the executor logs itself carry no level and stay out. +pub(crate) fn node_log_changes( + node_key: &str, + events: &[LifeCycleEvent], +) -> Vec<(String, RunChange)> { + events + .iter() + .filter(|event| matches!(event.kind, LifeCycleEventKind::Log) && event.level.is_some()) + .take(NODE_LOGS_PER_NODE) + .enumerate() + .map(|(index, event)| { + ( + format!("node-log/{node_key}/{index}"), + RunChange::NodeLog { + node_key: node_key.to_owned(), + level: match event.level { + Some(LogLevel::Warning) => NodeLogLevel::Warning, + Some(LogLevel::Error) => NodeLogLevel::Error, + Some(LogLevel::Info) | None => NodeLogLevel::Info, + }, + message: bounded(&event.content), + }, + ) + }) + .collect() +} + +/// What was lost when some of a run's output could not be sent, and the warning reporting it under the run; `None` when nothing was lost. +pub(crate) fn upload_loss(summary: &UploadSummary) -> Option<(String, RunChange)> { + let failure: String = summary + .failure + .clone() + .map_or_else(String::new, |failure| format!(": {failure}")); + (summary.dropped_bytes > 0 || summary.failure.is_some()).then(|| { + let message: String = bounded(&format!( + "{} bytes of run output were not stored{failure}", + summary.dropped_bytes + )); + ( + message.clone(), + RunChange::NodeLog { + node_key: RUN_OUTPUT_NODE.to_owned(), + level: NodeLogLevel::Warning, + message, + }, + ) + }) +} + +/// `message` without NUL, which PostgreSQL refuses in text and JSON, cut to its limit at a character boundary, ending in an ellipsis when cut. +fn bounded(message: &str) -> String { + let message: String = message.replace('\0', ""); + if message.len() <= NODE_LOG_MESSAGE_BYTES { + return message; + } + let room: usize = NODE_LOG_MESSAGE_BYTES - ELLIPSIS.len_utf8(); + let end: usize = (0..=room) + .rev() + .find(|index| message.is_char_boundary(*index)) + .unwrap_or(0); + format!("{}{ELLIPSIS}", &message[..end]) +} diff --git a/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs b/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs index 0979bdb473..cfeeda589d 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/main/mod.rs @@ -7,3 +7,4 @@ pub mod providers_document; pub mod python_declarations; pub mod register_snapshot; pub mod resource_nodes; +pub mod saved_discovered_sets; diff --git a/crates/sqlbuild-python-project/src/project_snapshot/main/saved_discovered_sets.rs b/crates/sqlbuild-python-project/src/project_snapshot/main/saved_discovered_sets.rs new file mode 100644 index 0000000000..2bf9948f24 --- /dev/null +++ b/crates/sqlbuild-python-project/src/project_snapshot/main/saved_discovered_sets.rs @@ -0,0 +1,33 @@ +//! The discovered sets a claimed run's snapshot saved, read before the worker compiles. + +use pyo3::exceptions::PyRuntimeError; +use pyo3::prelude::{PyResult, Python}; +use sqlbuild_orchestration::discovered_sets::types::DiscoveredSets; +use sqlbuild_orchestration::worker::main::connect_worker::connect_worker; +use sqlbuild_orchestration::worker::main::fetch_execution::fetch_execution; +use uuid::Uuid; + +/// The sets the server saved for a claimed run, so the worker compiles the published nodes. +pub fn saved_discovered_sets( + py: Python<'_>, + (server_url, bearer): (&str, &str), + (run_id, claim_id): (&str, &str), +) -> PyResult { + let identity = ( + Uuid::parse_str(run_id).map_err(|error| PyRuntimeError::new_err(error.to_string()))?, + Uuid::parse_str(claim_id).map_err(|error| PyRuntimeError::new_err(error.to_string()))?, + ); + py.detach(|| { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| PyRuntimeError::new_err(error.to_string()))?; + runtime + .block_on(async { + let client = connect_worker(server_url, bearer, identity)?; + fetch_execution(&client).await + }) + .map(|execution| execution.discovered) + .map_err(|error| PyRuntimeError::new_err(error.to_string())) + }) +} diff --git a/crates/sqlbuild-python-project/src/project_snapshot/models.rs b/crates/sqlbuild-python-project/src/project_snapshot/models.rs index 8738fbbc28..25bf7aab65 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/models.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/models.rs @@ -1,15 +1,20 @@ //! Public records of project snapshot. +use crate::compiled_project::constants::HARD_SKIP_MODE; use crate::compiled_project::constants::NO_CHANGE_REASON; +use crate::compiled_project::constants::PROGRESS_INTERVAL; use crate::compiled_project::constants::REPORT_ATTEMPTS; use crate::compiled_project::constants::SKIP_ACTION; use crate::compiled_project::constants::SQL_TEST_KEY_PREFIX; use crate::compiled_project::constants::STORE_BUSY_STATUS; +use crate::compiled_project::constants::UNCHANGED_REASON; +use crate::native_host::main::write_stderr_line::write_stderr_line; use crate::native_host::models::DeferredCost; -use crate::project_snapshot::_helpers::snapshot::snapshot_execution::Completion; use crate::project_snapshot::_helpers::snapshot::snapshot_execution::is_function; +use crate::project_snapshot::_helpers::snapshot::snapshot_execution::planned_key; use crate::project_snapshot::_helpers::snapshot::snapshot_execution::poisoned; use crate::project_snapshot::_helpers::snapshot::snapshot_execution::severity; +use crate::project_snapshot::_helpers::snapshot::snapshot_logs::{node_log_changes, upload_loss}; use crate::project_snapshot::_helpers::snapshot::snapshot_worker::WorkerOwner; use crate::project_snapshot::_helpers::snapshot::snapshot_worker::unavailable; use crate::project_snapshot::types::NodeKeys; @@ -25,12 +30,18 @@ use pyo3::prelude::PyResult; use pyo3::prelude::Python; use pyo3::pyclass; use pyo3::pymethods; +use pyo3::types::PyDict; +use pyo3::types::PyDictMethods; use pyo3::types::PyStringMethods; use sqlbuild_core::models::ResourceKind; use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; +use sqlbuild_host::models::LifeCycleEvent; use sqlbuild_host::models::SqlTestOutcome; use sqlbuild_host::types::ResultEnum; use sqlbuild_orchestration::api::errors::ClientError; +use sqlbuild_orchestration::run_output::constants::UPLOAD_CLOSE_BUDGET; +use sqlbuild_orchestration::run_output::main::finish_output_upload::finish_output_upload; +use sqlbuild_orchestration::run_output::main::start_output_upload::start_output_upload; use sqlbuild_orchestration::runs::models::NodeOutcome; use sqlbuild_orchestration::runs::models::RunChange; use sqlbuild_orchestration::runs::models::RunCommand; @@ -43,6 +54,7 @@ use sqlbuild_orchestration::snapshots::models::SnapshotRecord; use sqlbuild_orchestration::worker::errors::WorkerError; use sqlbuild_orchestration::worker::main::connect_worker::connect_worker; use sqlbuild_orchestration::worker::main::start_worker::start_worker; +use sqlbuild_python_base::native_host::types::ReadResult; use sqlbuild_python_base::records::main::fields::field::field; use sqlbuild_state::runs::constants::FIRST_ATTEMPT; use sqlbuild_state::runs::constants::SYSTEM_RETRY_USER; @@ -57,6 +69,7 @@ use std::sync::Mutex; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; +use std::time::Instant; use uuid::Uuid; use crate::project_snapshot::constants::MISSING_SECRET_CODE; @@ -124,6 +137,49 @@ impl NativeOrchestrationSnapshot { } } +/// Rows a running node has written, unknown once a batch reports no count, and the last report sent. +#[derive(Clone, Copy, Debug)] +pub(crate) struct RowProgress { + pub(crate) rows: Option, + pub(crate) reported: Option<(Instant, i64)>, +} + +/// A finished node's result as the worker reports it. +#[derive(Clone, Debug)] +pub(crate) struct Completion { + pub(crate) outcome: NodeOutcome, + pub(crate) rows_affected: Option, + /// The rows a fully rebuilt table holds, where the warehouse's metadata count is exact. + pub(crate) table_rows: Option, + pub(crate) no_change_reason: Option, + pub(crate) error_code: Option, + pub(crate) error_message: Option, + /// The node skipped itself with a hard skip, so the nodes it blocks name it as their cause. + pub(crate) skipped_itself: bool, +} + +impl Completion { + pub(crate) const fn of(outcome: NodeOutcome) -> Self { + Self { + outcome, + rows_affected: None, + table_rows: None, + no_change_reason: None, + error_code: None, + error_message: None, + skipped_itself: false, + } + } + + /// A node that is up to date succeeds without building, saying why. + pub(crate) fn unchanged() -> Self { + Self { + no_change_reason: Some(UNCHANGED_REASON.into()), + ..Self::of(NodeOutcome::Success) + } + } +} + /// This transient owner records only acknowledged outcomes; durable lifecycle remains on the API. #[derive(Debug)] pub struct WorkerBuild { @@ -141,6 +197,8 @@ pub struct WorkerBuild { held: Mutex>, /// Each snapshot node's direct upstream node keys, for naming what a skipped node waited on. upstream: BTreeMap>, + /// The build plan's upstream edges, which also join loaders that depend on other loaders. + planned_upstream: Mutex>>, /// The failed node each finished node traces back to: itself when it failed, its cause when skipped. causes: Mutex>, /// The worst attached outcome of each node, for commands that only run tests or audits. @@ -153,6 +211,8 @@ pub struct WorkerBuild { ignored_audit_failures: AtomicU32, /// The build's cost finalization, collected once the run has reported its outcome. deferred_cost: DeferredCost, + /// Rows each running node has written so far, and when the worker last reported them. + progress: Mutex>, } impl WorkerBuild { @@ -170,15 +230,22 @@ impl WorkerBuild { untested: Mutex::default(), held: Mutex::default(), upstream, + planned_upstream: Mutex::default(), causes: Mutex::default(), checked: Mutex::default(), returned: AtomicBool::new(false), ignored_audit_failures: AtomicU32::new(0), refusal: Mutex::default(), deferred_cost: DeferredCost::default(), + progress: Mutex::default(), }); + worker.get().with_owner(worker.py(), |owner| { + start_output_upload(&owner.client) + .map(drop) + .map_err(|error| PyRuntimeError::new_err(error.to_string())) + })?; for key in state.execution.skipped_nodes.keys() { - state.complete(worker.py(), key, (NodeOutcome::Skipped, None, (None, None)))?; + state.complete(worker.py(), key, Completion::of(NodeOutcome::Skipped))?; } Ok(state) } @@ -192,6 +259,12 @@ impl WorkerBuild { self.execution.claim.request.run_id } + /// The first server run of this run's rerun chain; the run itself unless it reruns another. + pub fn root_run_id(&self) -> uuid::Uuid { + let request = &self.execution.claim.request; + request.chain_run_id.unwrap_or(request.run_id) + } + /// What the runs table records of the server run this build executes. pub fn server_run(&self) -> ServerRun { let request = &self.execution.claim.request; @@ -269,11 +342,11 @@ impl WorkerBuild { self.complete( py, key, - ( - NodeOutcome::Failed, - None, - (Some(MISSING_SECRET_CODE.to_owned()), Some(message.clone())), - ), + Completion { + error_code: Some(MISSING_SECRET_CODE.to_owned()), + error_message: Some(message.clone()), + ..Completion::of(NodeOutcome::Failed) + }, )?; } self.refuse(reason) @@ -305,6 +378,7 @@ impl WorkerBuild { self.check_cancelled(pipeline.py())?; let plan = field(pipeline, "plan_output")?; self.count_planned_tests(&plan)?; + self.record_planned_upstream(&plan)?; for collection in [ "model_entries", "seed_entries", @@ -327,18 +401,33 @@ impl WorkerBuild { if kind == ResourceKind::Model.as_str() && field(&entry, "action")?.str()?.to_str()? == SKIP_ACTION { - let outcome = if field(&entry, "reason")?.str()?.to_str()? == NO_CHANGE_REASON { - NodeOutcome::Success - } else { - NodeOutcome::Skipped - }; - self.complete(pipeline.py(), &key, (outcome, None, (None, None)))?; + let completion = + if field(&entry, "reason")?.str()?.to_str()? == NO_CHANGE_REASON { + Completion::unchanged() + } else { + Completion::of(NodeOutcome::Skipped) + }; + self.complete(pipeline.py(), &key, completion)?; } } } Ok(()) } + /// Keep the plan's upstream edges, keyed `:`, so a skip names a blocker the snapshot does not link. + fn record_planned_upstream(&self, plan: &Bound<'_, PyAny>) -> PyResult<()> { + let mut planned = self.planned_upstream.lock().map_err(|_| poisoned())?; + let edges = field(plan, "upstream_deps")?; + for (node, deps) in edges.cast::()?.iter() { + let mut keys: Vec = Vec::new(); + for dep in deps.try_iter()? { + keys.push(planned_key(&dep?)?); + } + planned.insert(planned_key(&node)?, keys); + } + Ok(()) + } + /// Count each function's tests this build plans, so a built function waits only for tests that will report. fn count_planned_tests(&self, plan: &Bound<'_, PyAny>) -> PyResult<()> { let mut untested = self.untested.lock().map_err(|_| poisoned())?; @@ -356,7 +445,7 @@ impl WorkerBuild { /// Nodes `build --changed` leaves unbuilt are up to date, as a planner `no_change` skip is. pub fn unchanged(&self, py: Python<'_>, keys: &[String]) -> PyResult<()> { for key in keys { - self.complete(py, key, (NodeOutcome::Success, None, (None, None)))?; + self.complete(py, key, Completion::unchanged())?; } Ok(()) } @@ -367,27 +456,17 @@ impl WorkerBuild { self.complete( py, key, - ( - NodeOutcome::Skipped, - None, - (None, Some(format!("held back: {why}"))), - ), + Completion { + error_message: Some(format!("held back: {why}")), + ..Completion::of(NodeOutcome::Skipped) + }, )?; } Ok(()) } /// A skip in a build names the failed node upstream of it; a test or audit run that raised skips what it never checked, with no cause. - fn complete( - &self, - py: Python<'_>, - key: &str, - (outcome, rows_affected, (error_code, error_message)): ( - NodeOutcome, - Option, - (Option, Option), - ), - ) -> PyResult<()> { + fn complete(&self, py: Python<'_>, key: &str, completion: Completion) -> PyResult<()> { if !self.execution.claim.request.selection.contains(key) { return Ok(()); } @@ -399,28 +478,40 @@ impl WorkerBuild { { return Ok(()); } - let skipped_because_of = match outcome { - NodeOutcome::Skipped => match self.execution.skipped_nodes.get(key) { - Some(cause) => Some(cause.clone()), - None if !self.checks_only() => self.failed_upstream(key)?, - None => None, - }, + let upstream = match completion.outcome { + NodeOutcome::Skipped | NodeOutcome::NotRun => { + match self.execution.skipped_nodes.get(key) { + Some(cause) => Some(cause.clone()), + None if !self.checks_only() => self.failed_upstream(key)?, + None => None, + } + } _ => None, }; + let outcome = match (completion.outcome, &upstream) { + (NodeOutcome::NotRun, Some(_)) => NodeOutcome::Skipped, + (outcome, _) => outcome, + }; + let skipped_because_of = upstream.filter(|_| outcome == NodeOutcome::Skipped); self.worker.bind(py).get().change( py, &format!("node-finished/{key}"), RunChange::NodeFinished { node_key: key.into(), outcome, - rows_affected, - error_code, + rows_affected: completion.rows_affected, + table_rows: completion.table_rows, + no_change_reason: completion.no_change_reason, + error_code: completion.error_code, skipped_because_of: skipped_because_of.clone(), - error_message: error_message.as_deref().map(redact_error_text), + error_message: completion.error_message.as_deref().map(redact_error_text), }, )?; let cause = match outcome { NodeOutcome::Failed => Some(key.to_owned()), + NodeOutcome::Skipped if completion.skipped_itself => { + skipped_because_of.or_else(|| Some(key.to_owned())) + } _ => skipped_because_of, }; if let Some(cause) = cause { @@ -457,6 +548,16 @@ impl WorkerBuild { self.record_start(py, key) } + /// `start_key` of the asset `name`. + pub fn start_asset(&self, py: Python<'_>, name: &str) -> PyResult<()> { + self.start_key(py, &format!("asset:{name}")) + } + + /// The asset `name` was running when the run was cancelled. + pub fn cancel_asset(&self, py: Python<'_>, name: &str) -> PyResult<()> { + self.finish_key(py, &format!("asset:{name}"), NodeOutcome::Cancelled) + } + /// `start_key` without the cancellation check. fn record_start(&self, py: Python<'_>, key: &str) -> PyResult<()> { if self.execution.claim.request.selection.contains(key) @@ -479,7 +580,7 @@ impl WorkerBuild { /// Report a selected node's outcome when the command reports no executor result for it. pub fn finish_key(&self, py: Python<'_>, key: &str, outcome: NodeOutcome) -> PyResult<()> { - self.complete(py, key, (outcome, None, (None, None))) + self.complete(py, key, Completion::of(outcome)) } /// A test or audit the snapshot records has started; a selected SQL test reports as a node. @@ -547,7 +648,7 @@ impl WorkerBuild { outcome }; if self.execution.claim.request.selection.contains(key) { - self.complete(py, key, (outcome, None, (None, None)))?; + self.complete(py, key, Completion::of(outcome))?; } else { self.finish_check(py, key, outcome)?; } @@ -571,10 +672,12 @@ impl WorkerBuild { /// The failed node nearest upstream of `key` in this run, or the cause a skipped one carries. fn failed_upstream(&self, key: &str) -> PyResult> { let causes = self.causes.lock().map_err(|_| poisoned())?; + let planned = self.planned_upstream.lock().map_err(|_| poisoned())?; let mut seen: BTreeSet<&str> = BTreeSet::from([key]); let mut pending: VecDeque<&str> = VecDeque::from([key]); while let Some(node) = pending.pop_front() { - for upstream in self.upstream.get(node).into_iter().flatten() { + let snapshot = self.upstream.get(node).into_iter().flatten(); + for upstream in snapshot.chain(planned.get(node).into_iter().flatten()) { if let Some(cause) = causes.get(upstream) { return Ok(Some(cause.clone())); } @@ -607,14 +710,15 @@ impl WorkerBuild { (false, true) => NodeOutcome::Cancelled, (false, false) => NodeOutcome::Failed, }; - self.complete(py, &key, (node, None, (error.clone(), message.clone())))?; + let failure = |outcome| Completion { + error_code: error.clone(), + error_message: message.clone(), + ..Completion::of(outcome) + }; + self.complete(py, &key, failure(node))?; if !passed && !cancelled { for model in self.blocked.get(&key).into_iter().flatten() { - self.complete( - py, - model, - (NodeOutcome::Failed, None, (error.clone(), message.clone())), - )?; + self.complete(py, model, failure(NodeOutcome::Failed))?; } } self.release_tested(py, &key) @@ -647,7 +751,7 @@ impl WorkerBuild { /// Publish a node's result, or hold a built function's while its tests have still to report. fn complete_or_hold(&self, py: Python<'_>, key: &str, completion: Completion) -> PyResult<()> { let waiting = !self.checks_only() - && matches!(completion.0, NodeOutcome::Success | NodeOutcome::Warn) + && matches!(completion.outcome, NodeOutcome::Success | NodeOutcome::Warn) && self .untested .lock() @@ -664,6 +768,56 @@ impl WorkerBuild { self.complete(py, key, completion) } + /// Add a finished batch's rows to a node's progress; a batch with no row count leaves its total unknown. + pub fn batch_rows(&self, py: Python<'_>, key: &str, rows: Option) -> PyResult<()> { + let total = { + let mut progress = self.progress.lock().map_err(|_| poisoned())?; + let node = progress.entry(key.into()).or_insert(RowProgress { + rows: Some(0), + reported: None, + }); + node.rows = node.rows.zip(rows).map(|(total, batch)| total + batch); + node.rows + }; + match total { + Some(total) => self.rows_written(py, key, total), + None => Ok(()), + } + } + + /// Report the rows a running node has written so far, at most once every few seconds per node. + pub fn rows_written(&self, py: Python<'_>, key: &str, total: i64) -> PyResult<()> { + if !self.execution.claim.request.selection.contains(key) { + return Ok(()); + } + let due = { + let mut progress = self.progress.lock().map_err(|_| poisoned())?; + let node = progress.entry(key.into()).or_insert(RowProgress { + rows: Some(total), + reported: None, + }); + node.rows = Some(total); + let due = node + .reported + .is_none_or(|(at, rows)| rows != total && at.elapsed() >= PROGRESS_INTERVAL); + if due { + node.reported = Some((Instant::now(), total)); + } + due + }; + if !due { + return Ok(()); + } + self.worker.bind(py).get().change( + py, + &format!("node-progress/{key}/{total}"), + RunChange::NodeProgress { + node_key: key.into(), + rows_so_far: total, + }, + ) + } + /// Existing native progress callbacks publish selected-node evidence without Python relays. pub fn completed(&self, result: &Bound<'_, PyAny>, key: &str) -> PyResult<()> { if key.starts_with(SQL_TEST_KEY_PREFIX) { @@ -700,19 +854,56 @@ impl WorkerBuild { ))); } }; - let rows = match result.getattr_opt("rows_affected")? { + let rows_affected = match result.getattr_opt("rows_affected")? { Some(value) => value.extract()?, None => None, }; + let table_rows = match result.getattr_opt("table_rows")? { + Some(value) => value.extract()?, + None => None, + }; + let skip_mode: Option = match result.getattr_opt("skip_mode")? { + Some(value) if !value.is_none() => Some(value.str()?.extract()?), + _ => None, + }; let error = match result.getattr_opt("error_code")? { Some(value) => value.extract()?, None => None, }; - let message = match result.getattr_opt("error_message")? { + let detail: Option = match result.getattr_opt("error_detail")? { Some(value) => value.extract()?, None => None, }; - self.complete_or_hold(result.py(), key, (outcome, rows, (error, message)))?; + let message: Option = match detail { + Some(detail) => Some(detail), + None => match result.getattr_opt("error_message")? { + Some(value) => value.extract()?, + None => None, + }, + }; + let events: Vec = match result.getattr_opt("lifecycle_events")? { + Some(value) => Vec::::read(&value)?, + None => Vec::new(), + }; + for (event_key, change) in node_log_changes(key, &events) { + self.worker + .bind(result.py()) + .get() + .change(result.py(), &event_key, change)?; + } + self.complete_or_hold( + result.py(), + key, + Completion { + rows_affected, + table_rows, + error_code: error, + error_message: message, + skipped_itself: outcome == NodeOutcome::Skipped + && skip_mode.as_deref() == Some(HARD_SKIP_MODE), + ..Completion::of(outcome) + }, + )?; } Ok(()) } @@ -795,7 +986,7 @@ impl WorkerBuild { }) }; if let Some(outcome) = outcome { - self.complete(py, key, (outcome, None, (None, None)))?; + self.complete(py, key, Completion::of(outcome))?; } } } @@ -815,9 +1006,9 @@ impl WorkerBuild { } else if returned && source_needs_no_run(key) { NodeOutcome::Success } else { - NodeOutcome::Skipped + NodeOutcome::NotRun }; - self.complete(py, key, (outcome, None, (None, None)))?; + self.complete(py, key, Completion::of(outcome))?; } let outcome = { let completed = self.completed.lock().map_err(|_| poisoned())?; @@ -829,7 +1020,10 @@ impl WorkerBuild { let bad = outcomes.iter().any(|value| { matches!( value, - NodeOutcome::Failed | NodeOutcome::Skipped | NodeOutcome::Cancelled + NodeOutcome::Failed + | NodeOutcome::Skipped + | NodeOutcome::Cancelled + | NodeOutcome::NotRun ) }); if cancelled { @@ -875,6 +1069,16 @@ impl WorkerBuild { .map_err(|_| poisoned())? .clone() .unwrap_or_else(|| "worker executor completed and closed its connections".into()); + let summary = py.detach(|| finish_output_upload(UPLOAD_CLOSE_BUDGET)); + if let Some((message, change)) = summary.as_ref().and_then(upload_loss) { + write_stderr_line(py, &format!("Run output: {message}\n"))?; + drop( + self.worker + .bind(py) + .get() + .change(py, "worker-output-loss", change), + ); + } let ignored: u32 = self.ignored_audit_failures.load(Ordering::SeqCst); if ignored > 0 { self.worker.bind(py).get().change( diff --git a/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs b/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs index 1c179e3ce4..187b50a6c3 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs @@ -56,6 +56,7 @@ use sqlbuild_python_front::discovery::main::project::configured_dynamic::configu use sqlbuild_python_front::native_host::main::recorder_callbacks::recorder_callbacks; use sqlbuild_python_output::build_progress::main::batch_complete_callback::batch_complete_callback; use sqlbuild_python_output::build_progress::main::check_callback::check_callback; +use sqlbuild_python_output::build_progress::main::rows_written_callback::rows_written_callback; use sqlbuild_python_output::build_progress::main::write_execution_header::write_execution_header; use sqlbuild_python_output::build_progress::models::BuildProgressCallbacks; use sqlbuild_python_output::build_progress::models::ConnectionProgressReporter; @@ -438,6 +439,7 @@ pub(crate) fn execute_build_plan<'py>( native_field(callbacks, "on_sub_progress")?, ), ("on_batch_complete", batch_complete_callback(callbacks)?), + ("on_rows_written", rows_written_callback(callbacks)?), ( "on_connection_start", native_field(connection, "on_connection_start")?, diff --git a/crates/sqlbuild-python/src/bindings/_helpers/build_command/lifecycle.rs b/crates/sqlbuild-python/src/bindings/_helpers/build_command/lifecycle.rs index 5c06a3d7d2..f1f8d86799 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/build_command/lifecycle.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/build_command/lifecycle.rs @@ -1,7 +1,7 @@ //! Ingress Python before the build and read-side assets dispatched as SQL completes. use std::collections::{BTreeMap, HashMap, HashSet}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use pyo3::exceptions::PyRuntimeError; use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult, Python}; @@ -36,6 +36,7 @@ use sqlbuild_python_project::graph::main::python_nodes::build_python_sql_run_lif use sqlbuild_python_project::graph::main::python_nodes::native_run_lifecycle::native_run_lifecycle; use sqlbuild_python_project::graph::main::python_nodes::python_node_graph::python_node_graph; use sqlbuild_python_project::planner_scope::main::build_intermediate_source_map::build_intermediate_source_map; +use sqlbuild_python_project::project_snapshot::models::WorkerBuild; const SUCCESS_STATUS: &str = "success"; const SKIPPED_STATUS: &str = "skipped"; @@ -55,7 +56,7 @@ fn node_rows(results: &Bound<'_, PyAny>) -> PyResult> { for result in results.try_iter()? { let result: Bound<'_, PyAny> = result?; rows.push(PythonNodeRow { - kind: native_field(&result, "kind")?.getattr("value")?.extract()?, + kind: native_field(&result, "kind")?.extract()?, node_name: native_field(&result, "node_name")?.extract()?, status: native_field(&result, "status")?.str()?.extract()?, error_message: native_field(&result, "error_message")?.extract()?, @@ -87,15 +88,44 @@ fn names_set<'py>(py: Python<'py>, names: &[String]) -> PyResult, + stream: Py, + use_color: bool, + worker: Option>, +} + +#[pymethods] +impl PythonNodeReporter { + /// A worker records an asset as running once it really starts. + fn started(&self, py: Python<'_>, name: &str) -> PyResult<()> { + self.worker + .as_ref() + .map_or(Ok(()), |worker| worker.start_asset(py, name)) + } + + /// A worker records an item that was running when the run was cancelled as cancelled. + fn cancelled(&self, py: Python<'_>, name: &str) -> PyResult<()> { + self.worker + .as_ref() + .map_or(Ok(()), |worker| worker.cancel_asset(py, name)) + } + + fn __call__(&self, py: Python<'_>, result: Bound<'_, PyAny>) -> PyResult<()> { + self.on_node_complete.bind(py).call1((&result,))?; + write_python_node_results(self.stream.bind(py), &tuple(py, &[result])?, self.use_color) + } +} + /// Mutable state of direct-mode Python lifecycle execution. #[pyclass(module = "sqlbuild._native", frozen)] pub(crate) struct DirectPythonLifecycle { plan: Py, discovered: Py, adapter: Py, - stream: Py, - use_color: bool, - base_on_node_complete: Py, + reporter: Py, read_side_connection: Mutex>>, read_side_tracker: Option>, ingress_python_results: Py, @@ -111,38 +141,24 @@ pub(crate) struct DirectPythonLifecycle { #[pymethods] impl DirectPythonLifecycle { - /// Record a finished SQL node, then dispatch and report newly ready Python nodes. + /// Record a finished SQL node, then dispatch newly ready Python nodes, each reported as it finishes. fn on_node_complete(&self, py: Python<'_>, node_result: Bound<'_, PyAny>) -> PyResult<()> { - let base: &Bound<'_, PyAny> = self.base_on_node_complete.bind(py); - base.call1((&node_result,))?; + self.reporter + .get() + .on_node_complete + .bind(py) + .call1((&node_result,))?; let Some(tracker) = &self.read_side_tracker else { return Ok(()); }; - let tracker: &Bound<'_, PyAny> = tracker.bind(py); - let previous: HashSet = result_names(&native_field(tracker, "results")?)?; - tracker.call_method1("record_sql_result", (node_result,))?; - let mut new_results: Vec> = Vec::new(); - for result in native_field(tracker, "results")?.try_iter()? { - let result: Bound<'_, PyAny> = result?; - if !previous.contains(&native_field(&result, "node_name")?.extract::()?) { - new_results.push(result); - } - } - self.report(py, &new_results) + tracker + .bind(py) + .call_method1("record_sql_result", (node_result,))?; + Ok(()) } } impl DirectPythonLifecycle { - fn report(&self, py: Python<'_>, results: &[Bound<'_, PyAny>]) -> PyResult<()> { - if results.is_empty() { - return Ok(()); - } - for result in results { - self.base_on_node_complete.bind(py).call1((result,))?; - } - write_python_node_results(self.stream.bind(py), &tuple(py, results)?, self.use_color) - } - /// Ingress results, then read-side results. pub(crate) fn python_results<'py>(&self, py: Python<'py>) -> PyResult> { let mut results: Vec> = self @@ -310,12 +326,13 @@ impl DirectPythonLifecycle { let Some(tracker) = &self.read_side_tracker else { return Ok(()); }; - let finalized: Vec> = tracker + let finalized: Bound<'_, PyAny> = tracker .bind(py) - .call_method0("finalize_unrun_python_nodes")? - .try_iter()? - .collect::>()?; - self.report(py, &finalized) + .call_method0("finalize_unrun_python_nodes")?; + for result in finalized.try_iter()? { + self.reporter.get().__call__(py, result?)?; + } + Ok(()) } } @@ -346,6 +363,8 @@ struct RuntimeParts<'a, 'py> { inputs: &'a LifecycleInputs<'py>, /// Each Python node's job warehouse, by name. warehouses: BTreeMap, + /// The first server run of a worker's rerun chain; `None` outside a worker. + root_run_id: Option, } fn node_runtime<'py>( @@ -381,6 +400,10 @@ fn node_runtime<'py>( "node_warehouses", pyo3::IntoPyObject::into_pyobject(parts.warehouses.clone(), py)?.into_any(), ), + ( + "chain_run_id", + pyo3::IntoPyObject::into_pyobject(parts.root_run_id.clone(), py)?.into_any(), + ), ], ) } @@ -533,7 +556,22 @@ pub(crate) fn prepare_direct_python_lifecycle<'py>( relations: (relation_targets, project_relations), inputs, warehouses: native_field(pipeline, "python_node_warehouses")?.extract()?, + root_run_id: context + .worker + .as_ref() + .map(|worker| worker.root_run_id().to_string()), }; + let reporter: Bound<'py, PythonNodeReporter> = Bound::new( + py, + PythonNodeReporter { + on_node_complete: inputs.on_node_complete.clone().unbind(), + stream: context.stream.clone().unbind(), + use_color: context.use_color, + worker: context.worker.clone(), + }, + )?; + let report = |method: &str| reporter.getattr(method); + let (on_asset_start, on_node_cancelled) = (report("started")?, report("cancelled")?); let mut ingress_python: Bound<'py, PyAny> = tuple(py, &[])?; let mut ingress_loads: Bound<'py, PyAny> = tuple(py, &[])?; if ingress_names.is_truthy()? { @@ -546,6 +584,8 @@ pub(crate) fn prepare_direct_python_lifecycle<'py>( ("use_color", boolean(py, context.use_color)), ("on_node_start", inputs.on_node_start.clone()), ("on_node_complete", inputs.on_node_complete.clone()), + ("on_asset_start", on_asset_start.clone()), + ("on_node_cancelled", on_node_cancelled.clone()), ], )?; call_with( @@ -597,28 +637,25 @@ pub(crate) fn prepare_direct_python_lifecycle<'py>( ("selected_python_names", names_set(py, &read_side)?), ("scheduled_sql_names", names_set(py, &scheduled)?), ("runtime", node_runtime(&parts, &connection)?), + ("on_node_complete", reporter.clone().into_any()), + ("on_asset_start", on_asset_start.clone()), + ("on_node_cancelled", on_node_cancelled.clone()), ], )?; for result in ingress_loads.try_iter()? { tracker.call_method1("record_sql_result", (result?,))?; } tracker.call_method0("dispatch_ready_python_nodes")?; - let initial: Bound<'py, PyAny> = native_field(&tracker, "results")?; - if initial.is_truthy()? { - write_python_node_results(&context.stream, &initial, context.use_color)?; - } read_side_tracker = Some(tracker.unbind()); } let (round_trip_gates, round_trip_waits) = round_trip_ordering(&lifecycle, &plan_output)?; - Bound::new( + let prepared = Bound::new( py, DirectPythonLifecycle { plan: plan_output.unbind(), discovered: discovered.unbind(), adapter: adapter.clone().unbind(), - stream: context.stream.clone().unbind(), - use_color: context.use_color, - base_on_node_complete: inputs.on_node_complete.clone().unbind(), + reporter: reporter.unbind(), read_side_connection: Mutex::new(read_side_connection), read_side_tracker, ingress_python_results: ingress_python.unbind(), @@ -628,7 +665,8 @@ pub(crate) fn prepare_direct_python_lifecycle<'py>( round_trip_waits, include_python, }, - ) + )?; + Ok(prepared) } type RoundTripGates = HashMap>; diff --git a/crates/sqlbuild-python/src/bindings/_helpers/build_command/planning.rs b/crates/sqlbuild-python/src/bindings/_helpers/build_command/planning.rs index ce74367d13..c484072646 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/build_command/planning.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/build_command/planning.rs @@ -18,6 +18,7 @@ use crate::bindings::_helpers::build_command::policies::enforce_plan_policies; use crate::bindings::_helpers::build_command::policies::model_limit; use crate::bindings::_helpers::command_runtime::audit_failures::resolve_ignore_audit_failures; use crate::bindings::_helpers::compile_driver::plan_pipeline::{SecretCheck, planned_project}; +use crate::bindings::_helpers::compile_driver::plan_result::PlanUse; use crate::bindings::_helpers::dbt_interop::reference_resolver::resolve_external_sql_reference_resolver; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::boundary::main::keywords::keywords; @@ -142,7 +143,7 @@ pub(crate) fn compile_build_plan<'py>(context: &BuildContext<'py>) -> PyResult( source_map: Option<&Bound<'py, PyAny>>, ) -> PyResult<()> { let py: Python<'py> = discovered_inputs.py(); - let record = |function: Bound<'py, PyAny>, result: Bound<'py, PyAny>| -> PyResult<()> { + let record = |result: Bound<'py, PyAny>| -> PyResult<()> { call_with( &native_field(run_state, "record_result")?, - &[("node_function", function), ("result", result)], + &[("result", result)], )?; Ok(()) }; @@ -130,17 +130,9 @@ pub(crate) fn record_python_run_state_results<'py>( let result: Bound<'py, PyAny> = result?; result_by_name.set_item(native_field(&result, "node_name")?, result)?; } - let node_by_name: Bound<'py, PyDict> = PyDict::new(py); for node in native_field(discovered_inputs, "asset_functions")?.try_iter()? { - let node: Bound<'py, PyAny> = node?; - node_by_name.set_item( - native_field(&node, "name")?, - native_field(&node, "function")?, - )?; - } - for (name, function) in node_by_name.iter() { - if let Some(result) = result_by_name.get_item(name)? { - record(function, result)?; + if let Some(result) = result_by_name.get_item(native_field(&node?, "name")?)? { + record(result)?; } } let by_loader: Bound<'py, PyDict> = match (source_map, load_results) { @@ -158,10 +150,7 @@ pub(crate) fn record_python_run_state_results<'py>( let Some(result) = by_loader.get_item(&name)? else { continue; }; - record( - native_field(&loader, "function")?, - load_result_as_python_result(&name, &result)?, - )?; + record(load_result_as_python_result(&name, &result)?)?; } Ok(()) } diff --git a/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs b/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs index c96449d454..fc7e7362ae 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs @@ -42,6 +42,7 @@ use pyo3::IntoPyObjectExt; use pyo3::exceptions::{PyAttributeError, PyOSError, PyTypeError, PyUnicodeError}; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyErr, PyResult, Python}; use pyo3::types::{PyDict, PyDictMethods, PyString, PyTuple}; +use sqlbuild_cli::argv::main::command_takes_option::command_takes_option; use sqlbuild_cli::diff_report::errors::DiffUserError; use sqlbuild_cli::diff_report::main::parse_diff_name_range::parse_diff_name_range; use sqlbuild_cli::dispatch::main::command_dispatch::command_dispatch; @@ -80,6 +81,9 @@ const RAW_QUERY_ATTRIBUTES: [&str; 4] = [ "right_query_file", ]; +/// The namespace attributes naming a command and the subcommand that can take `--allow-missing-secrets`. +const COMMAND_PATH_ATTRIBUTES: [&str; 2] = ["command", "rules_command"]; + /// The namespace attribute of `--allow-missing-secrets`. const ALLOW_MISSING_SECRETS_DEST: &str = "allow_missing_secrets"; @@ -456,6 +460,28 @@ fn run_implementation<'py>( code.into_bound_py_any(py) } +/// The secrets scope of one parsed command: its flag, whether it takes that flag, and its target. +fn secrets_scope(args: &Bound<'_, PyAny>) -> PyResult { + let allowed: bool = args + .getattr_opt(ALLOW_MISSING_SECRETS_DEST)? + .is_some_and(|allowed| allowed.is_truthy().unwrap_or(false)); + let mut command: Vec = Vec::new(); + for attribute in COMMAND_PATH_ATTRIBUTES { + let Some(value) = args.getattr_opt(attribute)? else { + continue; + }; + command.extend(optional_text(&value)?); + } + let command: Vec<&str> = command.iter().map(String::as_str).collect(); + Ok(MissingSecretsScope::enter( + ( + allowed, + command_takes_option(&command, ALLOW_MISSING_SECRETS_DEST), + ), + attribute(args, "target")?, + )) +} + /// Run `body` with the request record a parsed command's route passes, in the scopes `sqb` runs it in but the job scope, which the caller sets. pub(crate) fn with_routed_request<'py, T>( args: &Bound<'py, PyAny>, @@ -464,11 +490,7 @@ pub(crate) fn with_routed_request<'py, T>( let py: Python<'py> = args.py(); within(&warehouse_scope(args)?, |_| { let invocation = Invocation::new(args)?; - let _secrets = MissingSecretsScope::enter( - args.getattr_opt(ALLOW_MISSING_SECRETS_DEST)? - .is_some_and(|allowed| allowed.is_truthy().unwrap_or(false)), - attribute(args, "target")?, - ); + let _secrets = secrets_scope(args)?; let route = match command_dispatch(&command_facts(args)?) { Dispatch::Run(route, None) => route, Dispatch::Run(_, Some(failure)) | Dispatch::Fail(failure) => { @@ -493,11 +515,7 @@ fn routed_command<'py>( ) -> PyResult> { let py: Python<'py> = args.py(); let invocation = Invocation::new(args)?; - let _secrets = MissingSecretsScope::enter( - args.getattr_opt(ALLOW_MISSING_SECRETS_DEST)? - .is_some_and(|allowed| allowed.is_truthy().unwrap_or(false)), - attribute(args, "target")?, - ); + let _secrets = secrets_scope(args)?; match command_dispatch(&command_facts(args)?) { Dispatch::Nothing => 0.into_bound_py_any(py), Dispatch::Fail(failure) => Err(user_error(py, failure)), diff --git a/crates/sqlbuild-python/src/bindings/_helpers/cli/entry.rs b/crates/sqlbuild-python/src/bindings/_helpers/cli/entry.rs index a3e5e4b46e..fde1e9f431 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/cli/entry.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/cli/entry.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use std::time::{Instant, SystemTime}; -use pyo3::exceptions::{PyKeyboardInterrupt, PySystemExit}; +use pyo3::exceptions::{PyException, PyKeyboardInterrupt, PySystemExit}; use pyo3::prelude::{ Bound, Py, PyAny, PyAnyMethods, PyErr, PyModule, PyModuleMethods, PyResult, Python, }; @@ -15,6 +15,8 @@ use pyo3::{IntoPyObjectExt, pyfunction, wrap_pyfunction}; use sqlbuild_cli::dispatch::main::failure_report::failure_report; use sqlbuild_cli::dispatch::main::invocation_policy::invocation_policy; use sqlbuild_cli::dispatch::models::{CommandFacts, CommandFailure, InvocationPolicy}; +use sqlbuild_python_front::discovered_sets::main::set_discovery_source::set_discovery_source; +use sqlbuild_python_front::discovered_sets::models::{DiscoverySource, LiveDiscovery, Rediscover}; use sqlbuild_host::entries::models::{ExecutorHost, FacadeHost}; use sqlbuild_orchestration::runs::models::RunOutcome; @@ -398,8 +400,11 @@ fn exit<'py>(py: Python<'py>, code: i64) -> PyResult> { code.into_bound_py_any(py) } -/// The kind of expected failure `error` is, or `None` when it propagates. +/// The kind of expected failure `error` is, or `None` when it propagates. Every expected failure is an `Exception`, so Ctrl+C and SIGTERM propagate without loading the staying-Python failure classes. fn failure_kind(py: Python<'_>, error: &Bound<'_, PyAny>) -> PyResult> { + if !error.is_instance_of::() { + return Ok(None); + } if error.is_instance(&error_class(py, ErrorId::CliUser)?)? || error.is_instance(&error_class(py, ErrorId::Rules)?)? { @@ -655,7 +660,7 @@ fn observed_dispatch<'py>( &invocation.recall, ) { Ok(_) if terminated() => Err(CommandTerminated::new_err(TERMINATED_MESSAGE)), - Ok(_) if interrupted() => Err(PyKeyboardInterrupt::new_err(())), + _ if !terminated() && interrupted(py) => Err(PyKeyboardInterrupt::new_err(())), dispatched => dispatched, }; match dispatched { @@ -840,6 +845,23 @@ fn parsed_invocation<'py>( .map(|value| value.extract::>()) .transpose()? .flatten(); + if namespace + .get_item("discover")? + .is_some_and(|discover| discover.is_truthy().unwrap_or(false)) + { + let target: Option = namespace + .get_item("target")? + .map(|value| value.extract::>()) + .transpose()? + .flatten(); + set_discovery_source(DiscoverySource::Live(LiveDiscovery { + target, + previous: Default::default(), + rediscover: Rediscover::All, + keep_last_good: false, + seed: None, + })); + } if command.as_deref() == Some("location") && location_command.as_deref() == Some("runtime") { return within(&redirect_stdout_to_stderr(py)?, |_| { execute_parsed_invocation(args, handlers, identity, use_color) diff --git a/crates/sqlbuild-python/src/bindings/_helpers/cli/interruption.rs b/crates/sqlbuild-python/src/bindings/_helpers/cli/interruption.rs new file mode 100644 index 0000000000..ec01a60a68 --- /dev/null +++ b/crates/sqlbuild-python/src/bindings/_helpers/cli/interruption.rs @@ -0,0 +1,16 @@ +//! The `sqb` process's Ctrl+C handling, around the whole command. + +use pyo3::prelude::{Bound, PyAny, PyModule, PyModuleMethods, PyResult}; +use pyo3::{pyfunction, wrap_pyfunction}; + +use crate::bindings::_helpers::cli::termination::terminated; + +/// Call `run` as the `sqb` process's command and return its exit code, 130 once Ctrl+C stopped it. +#[pyfunction] +fn run_interruptible(run: &Bound<'_, PyAny>) -> PyResult { + sqlbuild_python_base::native_host::main::run_interruptible::run_interruptible(run, terminated) +} + +pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> { + module.add_function(wrap_pyfunction!(run_interruptible, module)?) +} diff --git a/crates/sqlbuild-python/src/bindings/_helpers/cli/mod.rs b/crates/sqlbuild-python/src/bindings/_helpers/cli/mod.rs index 7a3ebc8d8c..82b085cb09 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/cli/mod.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/cli/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod argv; pub(crate) mod dispatch; pub(crate) mod entry; pub(crate) mod failure_cause; +pub(crate) mod interruption; pub(crate) mod machine_output; pub(crate) mod namespace; pub(crate) mod observability; diff --git a/crates/sqlbuild-python/src/bindings/_helpers/cli/registration.rs b/crates/sqlbuild-python/src/bindings/_helpers/cli/registration.rs index c3c15b7c99..80cbd0e307 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/cli/registration.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/cli/registration.rs @@ -2,6 +2,7 @@ use pyo3::prelude::{Bound, PyModule, PyResult}; +use crate::bindings::_helpers::cli::interruption; use crate::bindings::_helpers::cli::{argv, entry, namespace, observability, termination}; use crate::bindings::_helpers::{ audit_command, build_command, build_progress, change_selection, check, clone, command_runtime, @@ -22,6 +23,7 @@ pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> { register_launch_state(module)?; namespace::register(module)?; observability::register(module)?; + interruption::register(module)?; termination::register(module)?; register_progress(module)?; register_progress_reporters(module)?; diff --git a/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_pipeline.rs b/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_pipeline.rs index b734fe7b1e..472e4a6866 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_pipeline.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_pipeline.rs @@ -12,6 +12,7 @@ use sqlbuild_rules::lint_text::main::counts_toward_exit::counts_toward_exit; use sqlbuild_rules::rule_results::main::default_rules_notice::default_rules_notice; use sqlbuild_rules::rule_results::main::format_skipped_models::format_skipped_models; +use crate::bindings::_helpers::compile_driver::plan_result::PlanUse; use crate::bindings::_helpers::compile_driver::plan_result::PlanningInputs; use crate::bindings::_helpers::compile_driver::plan_result::connection_with_hooks; use crate::bindings::_helpers::compile_driver::plan_result::pipeline_result; @@ -69,7 +70,7 @@ pub(crate) fn run_compile_pipeline<'py>( &arguments.value("adapter")?, ), (&arguments.value("options")?, arguments.value("hooks")?), - (None, None), + (None, None, PlanUse::Run), SecretCheck::Report, ) } @@ -78,7 +79,11 @@ pub(crate) fn run_compile_pipeline<'py>( pub(crate) fn planned_project<'py>( (discovered, adapter): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), (options, hooks): (&Bound<'py, PyAny>, Bound<'py, PyAny>), - (held, planned_through): (Option<&Bound<'py, PyAny>>, Option<&Bound<'py, PyAny>>), + (held, planned_through, plan_use): ( + Option<&Bound<'py, PyAny>>, + Option<&Bound<'py, PyAny>>, + PlanUse, + ), secrets: SecretCheck, ) -> PyResult> { let py: Python<'py> = discovered.py(); @@ -134,7 +139,7 @@ pub(crate) fn planned_project<'py>( planned( (discovered, adapter), (&options, &hooks), - (&compiled, planned_through), + (&compiled, planned_through, plan_use), ) } @@ -317,7 +322,11 @@ pub(crate) fn configured_rule_failures<'py>( fn planned<'py>( (discovered, adapter): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), (options, hooks): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), - (compiled, planned_through): (&Bound<'py, PyAny>, Option<&Bound<'py, PyAny>>), + (compiled, planned_through, plan_use): ( + &Bound<'py, PyAny>, + Option<&Bound<'py, PyAny>>, + PlanUse, + ), ) -> PyResult> { let py: Python<'py> = discovered.py(); let tracker: Bound<'py, PyAny> = timing_tracker(py)?; @@ -362,6 +371,7 @@ fn planned<'py>( adapter, connection: &opened, reads: &reads, + plan_use, node_results_location, }, &project, diff --git a/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_result.rs b/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_result.rs index 4ec8868c8b..54d8d779ce 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_result.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/compile_driver/plan_result.rs @@ -33,9 +33,11 @@ use pyo3::{IntoPyObjectExt, pyfunction, wrap_pyfunction}; use sqlbuild_python_base::boundary::models::KeywordArguments; use sqlbuild_python_base::native_host::main::connection_failure::connection_failure; use sqlbuild_python_base::native_host::main::host_entry::host_entry; +use sqlbuild_python_base::records::main::construct::new_plain_error::new_plain_error; use sqlbuild_python_base::records::main::fields::field::field as native_field; -use sqlbuild_python_base::records::types::RecordId; +use sqlbuild_python_base::records::types::{ErrorId, RecordId}; use sqlbuild_python_compile::compile_driver::main::stages::monotonic::monotonic; +use sqlbuild_python_front::discovered_sets::main::publish_only_placeholders::publish_only_placeholders; use sqlbuild_python_project::graph::main::python_nodes::run_selection_from_inputs::run_selection_from_inputs; const SINGLE_CONNECTION: i64 = 1; @@ -43,6 +45,15 @@ const SINGLE_CONNECTION: i64 = 1; /// The deferred relation locations and the warehouse relations behind them, when deferring. type Deferral<'py> = (Bound<'py, PyAny>, Bound<'py, PyAny>); +/// What the caller does with the plan it asks for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PlanUse { + /// Show it, placeholders included. + Show, + /// Run it, which refuses a selected placeholder. + Run, +} + /// The planning inputs: the discovered project, the adapter and its open connection. pub(crate) struct PlanningInputs<'a, 'py> { pub(crate) discovered_inputs: &'a Bound<'py, PyAny>, @@ -50,6 +61,7 @@ pub(crate) struct PlanningInputs<'a, 'py> { /// The live planning connection, `None` when the plan reads a synced state. pub(crate) connection: &'a Bound<'py, PyAny>, pub(crate) reads: &'a Bound<'py, PlannerReads>, + pub(crate) plan_use: PlanUse, /// Python nodes' `(database, schema)` under the active target. pub(crate) node_results_location: Option<(Option, Option)>, } @@ -103,6 +115,21 @@ fn without_loaders<'py>( )) } +/// Refuse to run a `for_each` asset that compiled as its placeholder because no discovery ran. +fn refuse_placeholders(discovered: &Bound<'_, PyAny>, selected: &Bound<'_, PyAny>) -> PyResult<()> { + let assets: Vec = publish_only_placeholders(discovered, selected)?; + match assets.first() { + None => Ok(()), + Some(asset) => Err(new_plain_error( + discovered.py(), + ErrorId::PlannerInput, + &format!( + "{asset} is discovered at publish; run it from a location or `sqb dev`, or pass --discover" + ), + )), + } +} + /// Plan the compiled project over an open connection and attach Python node plans. pub(crate) fn pipeline_result<'py>( inputs: &PlanningInputs<'_, 'py>, @@ -138,6 +165,9 @@ pub(crate) fn pipeline_result<'py>( ), (options, discovered, project), )?; + if inputs.plan_use == PlanUse::Run { + refuse_placeholders(discovered, &selected_python_node_names)?; + } python_read_source_names = python_read_source_names_for( py, Some(keywords( diff --git a/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/sqlbuild_work.rs b/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/sqlbuild_work.rs index aff62d6535..5726d4b46b 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/sqlbuild_work.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/sqlbuild_work.rs @@ -234,7 +234,7 @@ pub(crate) fn execute_dbt_sqlbuild_work<'py>( ), ], )?; - let result = call_with( + let ran = call_with( &host_entry(py, ExecutorHost::RunBuildPipeline)?, &[ ("plan", plan.clone()), @@ -247,7 +247,13 @@ pub(crate) fn execute_dbt_sqlbuild_work<'py>( ("runtime", runtime), ("callbacks", hooks), ], - )?; + ); + let closed = callbacks + .downcast::()? + .get() + .close(py); + let result = ran?; + closed?; let result = BuildExecutionResult::read(&result)?; write_runtime_target( &joined(&args.value("project_dir")?, &["target"])?, diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs index 266f0a043f..c77ac31612 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/command.rs @@ -21,6 +21,7 @@ use sqlbuild_orchestration::dev_events::models::{DevPhase, DevStepState}; use sqlbuild_orchestration::platform::models::LocationRuleFailure; use sqlbuild_orchestration::snapshots::models::SnapshotInput; use sqlbuild_orchestration::warehouse_metadata::models::WarehouseStateLocation; +use sqlbuild_python_compile::provider_check::main::key_secret_blocks::key_secret_blocks; use crate::bindings::_helpers::location_command::constants::EXECUTE_ACTION; use crate::bindings::_helpers::location_command::constants::PUBLISH_ACTION; @@ -35,15 +36,20 @@ use crate::bindings::_helpers::location_command::worker::execute_worker; use crate::bindings::_helpers::query_command::project::ProjectAdapter; use crate::bindings::_helpers::query_command::project::ProjectInputs; use crate::bindings::_helpers::query_command::project::project_adapter; +use sqlbuild_orchestration::discovered_sets::models::DiscoveryPublishRequest; use sqlbuild_python_base::boundary::models::KeywordArguments; use sqlbuild_python_base::native_host::main::write_console::write_console; use sqlbuild_python_base::records::main::construct::new_record_with::new_record_with; use sqlbuild_python_base::records::main::fields::field::field; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_compile::compile_driver::main::setup::compiled_phase::compiled_phase; +use sqlbuild_python_front::discovered_sets::main::discover_for_publication::discover_for_publication; +use sqlbuild_python_front::discovered_sets::main::set_discovery_source::set_discovery_source; +use sqlbuild_python_front::discovered_sets::models::DiscoverySource; use sqlbuild_python_output::recall::main::write_stderr::write_stderr; use sqlbuild_python_output::recall::models::InvocationRecall; use sqlbuild_python_project::compiled_views::models::NativeProjectView; +use sqlbuild_python_project::project_snapshot::main::saved_discovered_sets::saved_discovered_sets; use sqlbuild_python_project::project_snapshot::models::NativeOrchestrationSnapshot; use sqlbuild_python_project::project_snapshot::types::NodeKeys; @@ -297,6 +303,17 @@ pub(super) fn publish_location<'py>( .get("providers") .map(|providers| missing_provider_secrets(providers, &allowed)) .unwrap_or_default(); + let mut secrets_needed_by: BTreeMap> = BTreeMap::new(); + if missing_secrets.iter().any(|provider| !provider.allowed) { + let published: BTreeSet = snapshot.input.nodes.keys().cloned().collect(); + let project_view: Bound<'py, PyAny> = field(&compiled, "project")?; + for block in key_secret_blocks((&project.discovered, &project_view), &published)? { + secrets_needed_by.insert( + block.provider, + block.users.into_iter().chain(block.readers).collect(), + ); + } + } status(py, "Publishing location snapshot...")?; steps(py, &[(DevPhase::Publish, DevStepState::Started)], None)?; let record = snapshot.publication( @@ -320,6 +337,7 @@ pub(super) fn publish_location<'py>( refresh_at, state_locations: locations.into_iter().collect(), missing_secrets, + secrets_needed_by, }, (project.discovered, compiled), ))) @@ -358,6 +376,12 @@ pub(crate) fn run_location<'py>( arguments.value("run_id")?.extract::()?, arguments.value("claim_id")?.extract::()?, ); + let server_url: String = arguments.value("server_url")?.extract()?; + set_discovery_source(DiscoverySource::Saved(saved_discovered_sets( + py, + (&server_url, &bearer), + (&identity.0, &identity.1), + )?)); let ((snapshot, blocked, compiled), project) = compile_location(py, &arguments, &input)?; return execute_worker( py, @@ -375,6 +399,18 @@ pub(crate) fn run_location<'py>( return run_runtime(py, options.unwrap_or_else(|| PyDict::new(py))); } let publication = (|| { + discover_for_publication( + &arguments, + DiscoveryPublishRequest { + generation: arguments + .value("generation")? + .extract::>()? + .unwrap_or(1), + rediscover: None, + previous: Default::default(), + seed: true, + }, + )?; let (PublishedGeneration { record, .. }, _) = publish_location(py, &arguments)?.map_err(|failure| { PyValueError::new_err(format!( diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs index b97f5ec69f..e7b806b26a 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs @@ -29,9 +29,16 @@ use crate::bindings::_helpers::native_host::orchestration_sensors::{SensorCall, use crate::bindings::_helpers::native_host::warehouse_metadata::close_history_session; use crate::bindings::_helpers::native_host::warehouse_metadata::open_history_session; use crate::bindings::_helpers::native_host::warehouse_metadata::read_history; +use sqlbuild_orchestration::discovered_sets::constants::{CHECK_DISCOVERED_KEY, GENERATION_KEY}; +use sqlbuild_orchestration::discovered_sets::models::{ + DiscoveredSetCheck, DiscoveryPublishRequest, +}; use sqlbuild_python_base::boundary::main::error_text_fields::error_text_fields; use sqlbuild_python_base::boundary::main::within::within; use sqlbuild_python_base::native_host::main::redirect_stdout_to_stderr::redirect_stdout_to_stderr; +use sqlbuild_python_front::discovered_sets::main::checked_set::checked_set; +use sqlbuild_python_front::discovered_sets::main::discover_for_publication::discover_for_publication; +use sqlbuild_python_front::discovered_sets::main::published_sets::published_sets; use sqlbuild_python_output::recall::main::write_stderr::write_stderr; pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResult { @@ -53,13 +60,25 @@ pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResul }; let request: serde_json::Value = serde_json::from_str(&line).map_err(|_| { PyValueError::new_err( - "runtime expects a JSON generation, plan, metadata read, sensor evaluation or sensor trial per line", + "runtime expects a JSON publish request, plan, metadata read, sensor evaluation or sensor trial per line", ) })?; - let output = if let Some(generation) = request.as_i64() { + let publication: Option = request + .get(GENERATION_KEY) + .is_some() + .then(|| { + serde_json::from_value(request.clone()).map_err(|_| { + PyValueError::new_err("runtime received an invalid publish request") + }) + }) + .transpose()?; + let output = if let Some(publication) = publication { + let generation: i64 = publication.generation; options.set_item("generation", generation)?; let arguments = location_arguments(py, Some(options.clone()))?; held = None; + discover_for_publication(&arguments, publication)?; + let mut error_text: Option = None; let (published, rules) = match publish_location(py, &arguments) { Ok(Ok((published, project))) => { held = Some(project); @@ -75,13 +94,29 @@ pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResul let message = message.unwrap_or_else(|| error.to_string()); let failed = generation_failed(generation, message, (code, help)); py.detach(|| emit_dev_event(&failed))?; + error_text = Some(redact_error_text(&error.to_string())); (None, None) } }; + let (discovered, discover_files) = + published_sets(held.as_ref().map(|(discovered, _)| discovered))?; serde_json::to_string(&serde_json::json!({ "published": published, "rules": rules, + "discovered": discovered, + "discover_files": discover_files, + "error": error_text, })) + } else if request.get(CHECK_DISCOVERED_KEY).is_some() { + let check: DiscoveredSetCheck = serde_json::from_value(request.clone()) + .map_err(|_| { + PyValueError::new_err( + "runtime received an invalid discovered set check", + ) + })?; + let arguments = location_arguments(py, Some(options.clone()))?; + let held_discovered = held.as_ref().map(|(discovered, _)| discovered); + serde_json::to_string(&checked_set(&arguments, held_discovered, check)?) } else if let Some(plan) = request.get(PLAN_REQUEST) { serde_json::to_string(&runtime_plan(py, held.as_ref(), plan)?) } else if let Some(locations) = request.get(DYNAMIC_RESUME_REQUEST) { diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs index 52aff11f2f..94a20267ad 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/snapshot.rs @@ -10,11 +10,13 @@ use sqlbuild_analysis::planner_scope::main::node_loads::node_loads; use sqlbuild_core::models::DiagnosticSeverity; use sqlbuild_discovery::orchestration_files::models::OrchestrationInventory; use sqlbuild_discovery::project_validation::main::validate_orchestration_names::validate_orchestration_names; +use sqlbuild_orchestration::discovered_sets::constants::DISCOVERED_DOCUMENT; use sqlbuild_orchestration::snapshots::models::{SnapshotInput, SnapshotNode}; use sqlbuild_python_base::boundary::models::KeywordArguments; use sqlbuild_python_base::orchestration_reads::main::environment_hash::environment_hash; use sqlbuild_python_base::records::main::fields::field::field; use sqlbuild_python_front::command_runtime::main::published_concurrency::published_concurrency; +use sqlbuild_python_front::discovered_sets::main::used_discovered_sets::used_discovered_sets; use sqlbuild_python_front::discovery::main::project::named_node_rows::named_node_rows; use sqlbuild_python_front::discovery::main::project::project_facts::project_facts; use sqlbuild_python_front::discovery::main::project::validation_error::validation_error; @@ -107,6 +109,12 @@ pub(crate) fn orchestration_snapshot<'py>( if let Some(providers) = providers_document(&discovered_inputs, &input.nodes)? { input.documents.insert("providers".into(), providers); } + let sets = used_discovered_sets(); + if !sets.is_empty() { + let document = serde_json::to_value(&sets) + .map_err(|error| PyValueError::new_err(error.to_string()))?; + input.documents.insert(DISCOVERED_DOCUMENT.into(), document); + } let graph = project.lineage_graph(py)?; let inventory = if declared { orchestration_declarations(project_dir.clone().into_pyobject(py)?.as_any())? diff --git a/crates/sqlbuild-python/src/bindings/_helpers/native_host/discover_runner.rs b/crates/sqlbuild-python/src/bindings/_helpers/native_host/discover_runner.rs new file mode 100644 index 0000000000..18f0b8e405 --- /dev/null +++ b/crates/sqlbuild-python/src/bindings/_helpers/native_host/discover_runner.rs @@ -0,0 +1,101 @@ +//! Call one `@discover` function with a target's providers; only a location and `--discover` do. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyErr, PyResult, PyTypeMethods, Python}; +use pyo3::types::{PyBool, PyDict, PyDictMethods, PyFrozenSet, PyString}; +use sqlbuild_core::redaction::main::redact_masked_text::redact_masked_text; +use sqlbuild_host::entries::models::UserCodeHost; + +use crate::bindings::_helpers::native_host::setup_context::project_setup_context; +use sqlbuild_python_base::boundary::main::call_with::call_with; +use sqlbuild_python_base::boundary::main::within::within; +use sqlbuild_python_base::native_host::main::host_entry::host_entry as entry; +use sqlbuild_python_base::orchestration_reads::main::provider_secret_values::provider_secret_values; +use sqlbuild_python_base::records::main::fields::field::field as native_field; +use sqlbuild_python_front::discovery::main::python_files::discover_provider_classes::discover_provider_classes; +use sqlbuild_python_front::discovery::main::python_files::provider_by_name::provider_by_name; +use sqlbuild_python_front::discovery::main::python_files::provider_usages::provider_usages; +use sqlbuild_python_front::discovery::models::SecretPolicy; + +/// The result's JSON, or why the call failed with every provider secret masked. +pub(crate) fn run_discover<'py>( + py: Python<'py>, + (project_dir, target): (&Bound<'py, PyAny>, Option<&str>), + (record, assets): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), +) -> Result { + let providers = discover_provider_classes(project_dir.clone(), SecretPolicy::Defer.name()) + .map_err(|error| reason(py, &error, &[]))?; + let secrets: Vec = + provider_secret_values(&providers).map_err(|error| reason(py, &error, &[]))?; + called(py, (project_dir, target), (record, assets), providers) + .map_err(|error| reason(py, &error, &secrets)) +} + +fn called<'py>( + py: Python<'py>, + (project_dir, target): (&Bound<'py, PyAny>, Option<&str>), + (record, assets): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), + providers: Bound<'py, PyAny>, +) -> PyResult { + let function = native_field(record, "function")?; + let by_name = provider_by_name(&providers)?; + let target_name: Bound<'py, PyAny> = match target { + Some(target) => PyString::new(py, target).into_any(), + None => py.None().into_bound(py), + }; + let setup_context = project_setup_context( + (project_dir, &providers), + (&target_name, &py.None().into_bound(py)), + true, + )?; + let session = call_with( + &entry(py, UserCodeHost::BuildProviderSession)?, + &[ + ("discovered_providers", providers), + ("setup_context", setup_context), + ("allow_shared", PyBool::new(py, false).to_owned().into_any()), + ], + )?; + within(&session, |_| { + let arguments = PyDict::new(py); + for usage in provider_usages(&function, &by_name)?.try_iter()? { + let usage = usage?; + let instance = session.call_method1("get", (usage.getattr("provider_name")?,))?; + arguments.set_item(usage.getattr("parameter_name")?, instance)?; + } + let returned = function.call((), Some(&arguments))?; + let names = PyFrozenSet::new(py, by_name.keys())?; + call_with( + &entry(py, UserCodeHost::DiscoveredResultJson)?, + &[ + ("returned", returned), + ("functions", assets.clone()), + ("provider_names", names.into_any()), + ], + )? + .extract() + }) +} + +/// `error` as `Type: message`, without any of `secrets`; with NUL, under the rule shared with other error text. +fn reason(py: Python<'_>, error: &PyErr, secrets: &[String]) -> String { + let text: String = format!( + "{}: {}", + error + .get_type(py) + .name() + .map_or_else(|_| "Error".to_owned(), |name| name.to_string()), + error.value(py) + ); + let mask = |reading: &str| { + secrets + .iter() + .filter(|secret| !secret.is_empty()) + .fold(reading.to_owned(), |text, secret| { + text.replace(secret.as_str(), "***") + }) + }; + if text.contains('\0') { + return redact_masked_text(&text, mask); + } + mask(&text) +} diff --git a/crates/sqlbuild-python/src/bindings/_helpers/native_host/mod.rs b/crates/sqlbuild-python/src/bindings/_helpers/native_host/mod.rs index 4c5e9c4568..296da35165 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/native_host/mod.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/native_host/mod.rs @@ -1,5 +1,6 @@ //! Permanent Python host calls and compatibility views of native-owned execution data. +pub(crate) mod discover_runner; pub(crate) mod orchestration_sensors; pub(crate) mod registration; pub(crate) mod setup_context; diff --git a/crates/sqlbuild-python/src/bindings/_helpers/native_host/registration.rs b/crates/sqlbuild-python/src/bindings/_helpers/native_host/registration.rs index 3779722f71..dd19661d83 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/native_host/registration.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/native_host/registration.rs @@ -3,6 +3,9 @@ use pyo3::prelude::{Bound, PyModule, PyModuleMethods, PyResult}; use pyo3::types::PyTuple; use sqlbuild_host::entries::main::host_entry_labels::host_entry_labels; +use sqlbuild_python_front::discovered_sets::main::register_discover_runner::register_discover_runner; + +use crate::bindings::_helpers::native_host::discover_runner::run_discover; use sqlbuild_python_base::native_host::models::Dialect; use sqlbuild_python_planner::live_reads::main::register_live_reads::register_live_reads; @@ -16,5 +19,6 @@ pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> { register_exception_types(module)?; module.add_class::()?; register_live_reads(module)?; + register_discover_runner(run_discover); sqlbuild_python_base::orchestration_reads::main::register_orchestration_declarations::register_orchestration_declarations(module) } diff --git a/crates/sqlbuild-python/src/bindings/_helpers/plan_command/plan.rs b/crates/sqlbuild-python/src/bindings/_helpers/plan_command/plan.rs index d02e5ebb36..c36a1b80b8 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/plan_command/plan.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/plan_command/plan.rs @@ -28,6 +28,7 @@ use crate::bindings::_helpers::command_runtime::runtime_errors::raised; use crate::bindings::_helpers::compile_driver::plan_pipeline::{ SecretCheck, planned_project, selectors, }; +use crate::bindings::_helpers::compile_driver::plan_result::PlanUse; use crate::bindings::_helpers::compile_driver::rules_at_load::RulesAtLoadScope; use crate::bindings::_helpers::dbt_interop::reference_resolver::resolve_external_sql_reference_resolver; use crate::bindings::_helpers::plan_command::changed::changed_json; @@ -178,16 +179,14 @@ fn resolve_invocation<'py>( let discovered: Bound<'py, PyAny> = match project { PlanProject::Held { discovered, .. } => discovered.clone(), PlanProject::Compiled => timed(DISCOVERING, || { - let mut options: Vec<(&str, Bound<'py, PyAny>)> = vec![ + let options: [(&str, Bound<'py, PyAny>); 3] = [ ("project_dir", project_dir.clone()), ("extract_output_column_locations", flag(py, false)), - ]; - if state.is_some() { - options.push(( + ( "secret_policy", PyString::new(py, SecretPolicy::Defer.name()).into_any(), - )); - } + ), + ]; discover_project_inputs(py, Some(keywords(py, &options)?)) })?, }; @@ -375,6 +374,7 @@ fn compile_pipeline<'py>( PlanProject::Compiled => None, }, preview.as_ref(), + PlanUse::Show, ), SecretCheck::Report, ) @@ -550,7 +550,7 @@ pub(crate) fn run_plan_command(request: &Bound<'_, PyAny>) -> PyResult { Ok(plan(request, (PlanProject::Compiled, None))?.0) } -/// A location's preview from the synced `state`, without rules, which ran at load; vars or a dbt manifest recompile, deferring secrets. +/// A location's preview from the synced `state`, without rules, which ran at load; vars or a dbt manifest recompile. pub(crate) fn location_plan<'py>( request: &Bound<'py, PyAny>, (held, state): (PlanProject<'_, 'py>, &Arc), diff --git a/crates/sqlbuild-render/src/macro_calls/main/splice_macro_calls.rs b/crates/sqlbuild-render/src/macro_calls/main/splice_macro_calls.rs index c1a986e5b1..8744cc777a 100644 --- a/crates/sqlbuild-render/src/macro_calls/main/splice_macro_calls.rs +++ b/crates/sqlbuild-render/src/macro_calls/main/splice_macro_calls.rs @@ -1,13 +1,19 @@ //! Replace macro call sites with their rendered SQL and report each substitution span. +use std::borrow::Cow; + +use sqlbuild_sqltext::sql_scan::main::bounded_expansions::bounded_expansions; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; + use crate::macro_calls::_helpers::offsets::byte_offsets; use crate::macro_calls::models::MacroSpliceSpan; -/// Splice `outputs` over ascending code-point `sites`; `None` when they do not fit `sql`. +/// Splice `outputs`, bounded against comments, over ascending code-point `sites`; `None` when they do not fit `sql`. pub fn splice_macro_calls( sql: &str, sites: &[(usize, usize)], outputs: &[String], + syntax: Option<&LexicalSyntax>, ) -> Option<(String, Vec)> { if sites.len() != outputs.len() { return None; @@ -20,12 +26,26 @@ pub fn splice_macro_calls( return None; } let bytes = byte_offsets(sql, &boundaries)?; + let expansions: Vec<(usize, usize, &str)> = bytes + .as_chunks::<2>() + .0 + .iter() + .zip(outputs) + .map(|(range, output)| (range[0], range[1], output.as_str())) + .collect(); + let mut outputs: Vec> = outputs + .iter() + .map(|output| output.as_str().into()) + .collect(); + for bounded in bounded_expansions(sql, &expansions, syntax) { + outputs[bounded.index] = bounded.text.into(); + } let mut rendered = - String::with_capacity(sql.len() + outputs.iter().map(String::len).sum::()); + String::with_capacity(sql.len() + outputs.iter().map(|output| output.len()).sum::()); let mut spans = Vec::with_capacity(sites.len()); let mut cursor_byte = 0; let mut output_chars = 0; - for ((site, output), range) in sites.iter().zip(outputs).zip(bytes.as_chunks::<2>().0) { + for ((site, output), range) in sites.iter().zip(&outputs).zip(bytes.as_chunks::<2>().0) { let literal = &sql[cursor_byte..range[0]]; rendered.push_str(literal); output_chars += literal.chars().count(); diff --git a/crates/sqlbuild-render/src/macro_calls/tests/test_splice_macro_calls.rs b/crates/sqlbuild-render/src/macro_calls/tests/test_splice_macro_calls.rs index fc43f46ee6..4acadbc909 100644 --- a/crates/sqlbuild-render/src/macro_calls/tests/test_splice_macro_calls.rs +++ b/crates/sqlbuild-render/src/macro_calls/tests/test_splice_macro_calls.rs @@ -47,8 +47,8 @@ fn given_call_sites_and_outputs_when_splicing_then_sql_and_spans_match_python() .iter() .map(|output| (*output).to_owned()) .collect(); - let actual = - splice_macro_calls(test_case.sql, test_case.sites, &outputs).map(|(sql, spans)| { + let actual = splice_macro_calls(test_case.sql, test_case.sites, &outputs, None).map( + |(sql, spans)| { ( sql, spans @@ -63,7 +63,8 @@ fn given_call_sites_and_outputs_when_splicing_then_sql_and_spans_match_python() }) .collect::>(), ) - }); + }, + ); assert_eq!( actual, test_case diff --git a/crates/sqlbuild-sqltext/src/compiler/_helpers/sql_interpolation/substitution.rs b/crates/sqlbuild-sqltext/src/compiler/_helpers/sql_interpolation/substitution.rs index 6f4b7b1df6..6661388b25 100644 --- a/crates/sqlbuild-sqltext/src/compiler/_helpers/sql_interpolation/substitution.rs +++ b/crates/sqlbuild-sqltext/src/compiler/_helpers/sql_interpolation/substitution.rs @@ -3,6 +3,7 @@ use crate::compiler::models::CharSpan; use crate::compiler::models::{InterpolatedSql, InterpolationFailure, InterpolationRead}; use crate::compiler::types::InterpolationHost; +use crate::sql_scan::main::bounded_expansions::bounded_expansions; use crate::sql_scan::main::dialect_non_code_end::dialect_non_code_end; use crate::sql_scan::main::non_code_end::non_code_end; use crate::sql_scan::models::{QuotePolicy, Unclosed}; @@ -51,6 +52,7 @@ pub(crate) fn interpolate( } match run.scan(sql) { Ok(()) => { + run.bound_values(sql); let spans = character_spans(sql, &run.output, &run.spans); let changed = run.output != sql; Ok(InterpolatedSql { @@ -106,6 +108,39 @@ impl Interpolation<'_, H> { Ok(()) } + /// Keep the substituted values from opening or extending a comment, moving each span with them. + fn bound_values(&mut self, sql: &str) { + let values: Vec<(usize, usize, &str)> = self + .spans + .iter() + .map(|span| { + let value: &str = &self.output[span.output_start..span.output_end]; + (span.source_start, span.source_end, value) + }) + .collect(); + let bounded = bounded_expansions(sql, &values, self.host.lexical_syntax()); + if bounded.is_empty() { + return; + } + let mut texts: Vec = values + .iter() + .map(|(_, _, value)| (*value).to_owned()) + .collect(); + for value in bounded { + texts[value.index] = value.text; + } + self.output.clear(); + let mut copied: usize = 0; + for (span, text) in self.spans.iter_mut().zip(texts) { + self.output.push_str(&sql[copied..span.source_start]); + span.output_start = self.output.len(); + self.output.push_str(&text); + span.output_end = self.output.len(); + copied = span.source_end; + } + self.output.push_str(&sql[copied..]); + } + /// Python's `_interpolate_sql_segment`: every token inside one quoted literal. fn quoted_text(&mut self, sql: &str, start: usize, end: usize) -> Result<(), String> { let mut index = start; diff --git a/crates/sqlbuild-sqltext/src/sql_scan/_helpers/boundaries.rs b/crates/sqlbuild-sqltext/src/sql_scan/_helpers/boundaries.rs new file mode 100644 index 0000000000..0bf6709ec8 --- /dev/null +++ b/crates/sqlbuild-sqltext/src/sql_scan/_helpers/boundaries.rs @@ -0,0 +1,209 @@ +//! Where spliced text would open or extend a comment, read with the dialect's own scanner. + +use std::sync::LazyLock; + +use crate::sql_scan::_helpers::dialect::non_code_end; +use crate::sql_scan::constants::{BLOCK_COMMENT_OPEN, GENERIC_LINE_COMMENT_PREFIX}; +use crate::sql_scan::models::{BoundedExpansion, LexicalSyntax, Unclosed}; + +/// What callers without a dialect scan with: the comments every dialect has. +static GENERIC: LazyLock = LazyLock::new(|| LexicalSyntax { + line_comment_prefixes: vec![GENERIC_LINE_COMMENT_PREFIX.to_owned()], + ..LexicalSyntax::default() +}); +const SPACE: &str = " "; +const NEWLINE: &str = "\n"; + +/// What to put before and after one expansion. +#[derive(Clone, Copy, Default)] +struct Padding { + before: &'static str, + after: &'static str, +} + +/// The changed expansions, found up to the first unclosed quote or comment; texts that can't form a comment at a boundary are not scanned. +pub(crate) fn bounded( + sql: &str, + expansions: &[(usize, usize, &str)], + syntax: Option<&LexicalSyntax>, +) -> Vec { + let syntax: &LexicalSyntax = syntax.unwrap_or(&GENERIC); + if !may_form_comment(sql, expansions, syntax) { + return Vec::new(); + } + let mut walk = Walk { + syntax, + padding: vec![Padding::default(); expansions.len()], + code_before: None, + previous: None, + open_comment: None, + }; + let _unclosed: Result<(), Unclosed> = walk.over(sql, expansions); + walk.padding + .iter() + .zip(expansions) + .enumerate() + .filter(|(_, (padding, _))| !(padding.before.is_empty() && padding.after.is_empty())) + .map(|(index, (padding, (_, _, text)))| BoundedExpansion { + index, + text: format!("{}{text}{}", padding.before, padding.after), + lead: padding.before.len(), + }) + .collect() +} + +/// Whether any expansion holds a line comment or meets a neighbour in a comment opener. +fn may_form_comment( + sql: &str, + expansions: &[(usize, usize, &str)], + syntax: &LexicalSyntax, +) -> bool { + let mut before: Option = None; + let mut at: usize = 0; + for (start, end, text) in expansions { + let authored: &str = sql.get(at..*start).unwrap_or_default(); + for piece in [authored, *text] { + if meets_in_opener(before, piece.as_bytes().first().copied(), syntax) { + return true; + } + before = piece.as_bytes().last().copied().or(before); + } + if syntax + .line_comment_prefixes + .iter() + .any(|prefix| text.contains(prefix.as_str())) + { + return true; + } + at = *end; + } + let authored: &str = sql.get(at..).unwrap_or_default(); + meets_in_opener(before, authored.as_bytes().first().copied(), syntax) +} + +/// Whether `before` and `after`, side by side, open a comment. +fn meets_in_opener(before: Option, after: Option, syntax: &LexicalSyntax) -> bool { + let (Some(before), Some(after)) = (before, after) else { + return false; + }; + let pair: [u8; 2] = [before, after]; + pair == BLOCK_COMMENT_OPEN.as_bytes() + || syntax + .line_comment_prefixes + .iter() + .any(|prefix| prefix.as_bytes() == pair) +} + +/// One pass over the SQL as it will read once spliced. +struct Walk<'a> { + syntax: &'a LexicalSyntax, + padding: Vec, + /// The last byte so far, when it is code. + code_before: Option, + /// The last expansion placed in code. + previous: Option, + /// The expansion whose last line comment is still open. + open_comment: Option, +} + +impl Walk<'_> { + /// Walk the spliced text; a site inside a quote or comment is read as part of it. + fn over(&mut self, sql: &str, expansions: &[(usize, usize, &str)]) -> Result<(), Unclosed> { + let mut at: usize = 0; + for (index, (start, end, text)) in expansions.iter().enumerate() { + if *start < at { + continue; + } + at = self.read(sql.as_bytes(), (at, *start), None)?; + if at != *start { + continue; + } + let _read: usize = self.read(text.as_bytes(), (0, text.len()), Some(index))?; + self.previous = Some(index); + at = *end; + } + let _read: usize = self.read(sql.as_bytes(), (at, sql.len()), None)?; + Ok(()) + } + + /// Read one piece of authored or expanded text, returning where its last construct ends. + fn read( + &mut self, + bytes: &[u8], + (from, to): (usize, usize), + expansion: Option, + ) -> Result { + let mut index: usize = from; + while index < to { + let byte: u8 = bytes[index]; + if index == from && meets_in_opener(self.code_before, Some(byte), self.syntax) { + self.separate(expansion); + } + let end: Option = non_code_end(bytes, index, self.syntax)?; + let line_comment: bool = end.is_some() && self.opens_line_comment(&bytes[index..]); + self.close_comment( + &bytes[index..end.unwrap_or(index + 1)], + end.is_some(), + line_comment, + ); + match end { + None => { + self.code_before = Some(byte); + index += 1; + } + Some(end) => { + self.code_before = None; + if line_comment + && expansion.is_some() + && end == bytes.len() + && bytes[end - 1] != b'\n' + { + self.open_comment = expansion; + } + index = end; + } + } + } + Ok(index) + } + + /// A space between two bytes that open a comment, or a newline where a space opens one too. + fn separate(&mut self, expansion: Option) { + let space_opens: bool = meets_in_opener(self.code_before, Some(b' '), self.syntax); + let separator: &'static str = if space_opens { NEWLINE } else { SPACE }; + match (expansion, self.previous) { + (Some(current), _) => self.padding[current].before = separator, + (None, Some(previous)) => self.padding[previous].after = separator, + (None, None) => {} + } + } + + /// End the open comment's line before code; a line break or another line comment ends it already. + fn close_comment(&mut self, construct: &[u8], non_code: bool, line_comment: bool) { + let Some(open) = self.open_comment else { + return; + }; + if line_comment || construct.first() == Some(&b'\n') { + self.open_comment = None; + return; + } + let harmless: bool = if non_code { + construct.starts_with(BLOCK_COMMENT_OPEN.as_bytes()) && !construct.contains(&b'\n') + } else { + construct.iter().all(u8::is_ascii_whitespace) + }; + if !harmless { + self.padding[open].after = NEWLINE; + self.open_comment = None; + } + } + + fn opens_line_comment(&self, rest: &[u8]) -> bool { + !rest.starts_with(BLOCK_COMMENT_OPEN.as_bytes()) + && self + .syntax + .line_comment_prefixes + .iter() + .any(|prefix| rest.starts_with(prefix.as_bytes())) + } +} diff --git a/crates/sqlbuild-sqltext/src/sql_scan/_helpers/mod.rs b/crates/sqlbuild-sqltext/src/sql_scan/_helpers/mod.rs index 2f870bffee..51f6fe04db 100644 --- a/crates/sqlbuild-sqltext/src/sql_scan/_helpers/mod.rs +++ b/crates/sqlbuild-sqltext/src/sql_scan/_helpers/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod boundaries; pub mod dialect; pub mod dollar; pub mod parens; diff --git a/crates/sqlbuild-sqltext/src/sql_scan/main/bounded_expansions.rs b/crates/sqlbuild-sqltext/src/sql_scan/main/bounded_expansions.rs new file mode 100644 index 0000000000..e6184f77ad --- /dev/null +++ b/crates/sqlbuild-sqltext/src/sql_scan/main/bounded_expansions.rs @@ -0,0 +1,14 @@ +//! `bounded_expansions`: the one rule every textual substitution applies before it splices. + +use crate::sql_scan::_helpers::boundaries::bounded; +use crate::sql_scan::models::{BoundedExpansion, LexicalSyntax}; + +/// The expansions over ascending byte ranges of `sql` that need a space or newline so none opens or extends a comment; usually none. +#[must_use] +pub fn bounded_expansions( + sql: &str, + expansions: &[(usize, usize, &str)], + syntax: Option<&LexicalSyntax>, +) -> Vec { + bounded(sql, expansions, syntax) +} diff --git a/crates/sqlbuild-sqltext/src/sql_scan/main/expansion_followed_by.rs b/crates/sqlbuild-sqltext/src/sql_scan/main/expansion_followed_by.rs new file mode 100644 index 0000000000..fbb30c6cc9 --- /dev/null +++ b/crates/sqlbuild-sqltext/src/sql_scan/main/expansion_followed_by.rs @@ -0,0 +1,12 @@ +//! `expansion_followed_by`: an expansion as it stands before text wrapped around it. + +use crate::sql_scan::_helpers::boundaries::bounded; +use crate::sql_scan::models::LexicalSyntax; + +/// `text`, bounded so that `next` can be written straight after it. +#[must_use] +pub fn expansion_followed_by(text: &str, next: &str, syntax: Option<&LexicalSyntax>) -> String { + bounded(next, &[(0, 0, text)], syntax) + .pop() + .map_or_else(|| text.to_owned(), |expansion| expansion.text) +} diff --git a/crates/sqlbuild-sqltext/src/sql_scan/main/mod.rs b/crates/sqlbuild-sqltext/src/sql_scan/main/mod.rs index b75cc2205a..789cd5f5d9 100644 --- a/crates/sqlbuild-sqltext/src/sql_scan/main/mod.rs +++ b/crates/sqlbuild-sqltext/src/sql_scan/main/mod.rs @@ -1,8 +1,10 @@ +pub mod bounded_expansions; pub mod comment_end; pub mod dialect_lexical_syntax; pub mod dialect_matching_paren; pub mod dialect_non_code_end; pub mod dialect_non_code_ranges; +pub mod expansion_followed_by; pub mod follows_table_wrapper; pub mod lexical_syntax_key; pub mod matching_paren; diff --git a/crates/sqlbuild-sqltext/src/sql_scan/models.rs b/crates/sqlbuild-sqltext/src/sql_scan/models.rs index b89ffe1f8f..195d9ffacd 100644 --- a/crates/sqlbuild-sqltext/src/sql_scan/models.rs +++ b/crates/sqlbuild-sqltext/src/sql_scan/models.rs @@ -94,3 +94,13 @@ impl LexicalSyntax { .any(|value| value.as_bytes() == [quote]) } } + +/// An expansion that must change so that it neither opens nor extends a comment where it lands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BoundedExpansion { + /// Its position among the expansions given. + pub index: usize, + pub text: String, + /// The bytes, and characters, now ahead of the original text. + pub lead: usize, +} diff --git a/crates/sqlbuild-sqltext/src/sql_scan/tests.rs b/crates/sqlbuild-sqltext/src/sql_scan/tests.rs index 3da57ecf98..9b02b57cd4 100644 --- a/crates/sqlbuild-sqltext/src/sql_scan/tests.rs +++ b/crates/sqlbuild-sqltext/src/sql_scan/tests.rs @@ -1,3 +1,5 @@ +#[path = "tests/test_bounded_expansions.rs"] +mod bounded_expansions; #[path = "tests/test_dialect_scan.rs"] mod dialect_scan; #[path = "tests/helpers.rs"] diff --git a/crates/sqlbuild-sqltext/src/sql_scan/tests/helpers.rs b/crates/sqlbuild-sqltext/src/sql_scan/tests/helpers.rs index ad9f12b511..416c4ee73b 100644 --- a/crates/sqlbuild-sqltext/src/sql_scan/tests/helpers.rs +++ b/crates/sqlbuild-sqltext/src/sql_scan/tests/helpers.rs @@ -1,7 +1,9 @@ //! Shared lexical syntaxes for SQL scanning tests. use crate::sql_scan::_helpers::dollar::dollar_quote_end; +use crate::sql_scan::main::bounded_expansions::bounded_expansions; use crate::sql_scan::main::comment_end::comment_end; +use crate::sql_scan::main::dialect_non_code_ranges::dialect_non_code_ranges; use crate::sql_scan::main::quote_end::quote_end; use crate::sql_scan::models::{LexicalSyntax, QuotePolicy, Unclosed}; use crate::sql_scan::tests::test_types::DispatchTestCase; @@ -130,3 +132,158 @@ pub(crate) fn syntax(quotes: &[&str], flags: [bool; 4], prefixes: &[&str]) -> Le bracket_identifiers: false, } } + +/// Negatives, comments, comment halves, operators, quotes, empty text and newlines. +const HOSTILE: [&str; 44] = [ + "", + " ", + "\n", + "1", + "-1", + "- 1", + "-", + "--", + "---", + "-/", + "/", + "//", + "/ 2", + "*", + "**", + "*/", + "/**/", + "/* note */", + "/* two\nlines */", + "1 -- one", + "1 -- one\n", + "-- one", + "-- one\n2", + "1 // one", + "//x", + "#", + "#x", + "# x", + "1 # one", + "#!x", + "!x", + "+", + "<", + ">", + "|", + "'a--b'", + "'/*'", + "1-", + "1/", + "\n-1", + "-1\n", + "x -- a -- b", + "1 /* c */ -- d", + "\u{e9}-", +]; +/// `{}` marks each site, all of them in code. +const POSITIONS: [&str; 25] = [ + "{}", + "select {} as x, 7 as y", + "select -{} as x, 7 as y", + "select {}- 1", + "select {}-1", + "select a/{}", + "select {}/2", + "select {}*2", + "select a/{}*2", + "select {} -- note", + "select {} /* note */", + "select {} /* two\nlines */", + "select {} /* note */ , b", + "select {}\n, b", + "select {}\r\n, b", + "select {} \n, b", + "({})", + "f({}, 2)", + "{}_count", + "select {}'text'", + "select '--' || {}", + "/* c */{}", + "select {}{}", + "select -{}-1, {}", + "select {} {}\nfrom t", +]; + +/// `template` with `values` at its sites, as authored and once bounded. +pub(crate) fn spliced(template: &str, values: &[&str], syntax: &LexicalSyntax) -> (String, String) { + let mut sql: String = String::new(); + let mut sites: Vec<(usize, usize, &str)> = Vec::new(); + let mut pieces = template.split("{}"); + sql.push_str(pieces.next().unwrap_or_default()); + for (piece, value) in pieces.zip(values) { + sites.push((sql.len(), sql.len() + 2, value)); + sql.push_str("@v"); + sql.push_str(piece); + } + let mut texts: Vec = values.iter().map(|value| (*value).to_owned()).collect(); + for expansion in bounded_expansions(&sql, &sites, Some(syntax)) { + assert_eq!( + &expansion.text[expansion.lead..expansion.lead + values[expansion.index].len()], + values[expansion.index] + ); + texts[expansion.index] = expansion.text; + } + let joined = |texts: &[String]| { + template + .split("{}") + .zip(texts.iter().map(String::as_str).chain([""])) + .flat_map(|(piece, value)| [piece, value]) + .collect::() + }; + let raw: Vec = values.iter().map(|value| (*value).to_owned()).collect(); + (joined(&raw), joined(&texts)) +} + +/// The code and quoted text of `sql`, without whitespace or comments. +fn code(sql: &str, syntax: &LexicalSyntax) -> String { + let mut kept: String = String::new(); + let mut at: usize = 0; + for (start, end) in dialect_non_code_ranges(sql, syntax) { + kept.extend( + sql[at..start] + .chars() + .filter(|character| !character.is_whitespace()), + ); + let construct: &str = &sql[start..end]; + kept.extend(Some(construct).filter(|text| text.starts_with(['\'', '"', '`']))); + at = end; + } + kept.extend( + sql[at..] + .chars() + .filter(|character| !character.is_whitespace()), + ); + kept +} + +/// Each splice whose bounded text reads wrong, or changed although it read right. +pub(crate) fn generated_failures(syntax: &LexicalSyntax) -> Vec { + POSITIONS + .iter() + .flat_map(|template| { + HOSTILE.iter().flat_map(move |first| { + HOSTILE + .iter() + .map(move |second| (*template, [*first, *second, *first])) + }) + }) + .filter_map(|(template, values)| { + let sites: usize = template.matches("{}").count(); + let values: &[&str] = &values[..sites]; + let expected: String = template + .split("{}") + .zip(values.iter().copied().chain([""])) + .map(|(piece, value)| code(piece, syntax) + &code(value, syntax)) + .collect(); + let (raw, bounded) = spliced(template, values, syntax); + let read_right: bool = code(&raw, syntax) == expected; + let wrong: bool = code(&bounded, syntax) != expected || (read_right && bounded != raw); + wrong.then(|| format!("{template:?} with {values:?} gave {bounded:?}")) + }) + .collect() +} diff --git a/crates/sqlbuild-sqltext/src/sql_scan/tests/test_bounded_expansions.rs b/crates/sqlbuild-sqltext/src/sql_scan/tests/test_bounded_expansions.rs new file mode 100644 index 0000000000..3168007021 --- /dev/null +++ b/crates/sqlbuild-sqltext/src/sql_scan/tests/test_bounded_expansions.rs @@ -0,0 +1,127 @@ +//! An expansion never opens or extends a comment where it lands. + +use crate::sql_scan::main::dialect_lexical_syntax::dialect_lexical_syntax; +use crate::sql_scan::models::LexicalSyntax; +use crate::sql_scan::tests::helpers::{generated_failures, spliced}; +use crate::sql_scan::tests::test_types::{BoundaryTestCase, GeneratedBoundaryTestCase}; + +#[test] +fn given_hostile_expansions_in_every_position_when_bounded_then_only_changed_code_changes() { + let test_cases = [ + GeneratedBoundaryTestCase { + description: "generic", + syntax: dialect_lexical_syntax("duckdb"), + expected_failures: &[], + }, + GeneratedBoundaryTestCase { + description: "BigQuery", + syntax: dialect_lexical_syntax("bigquery"), + expected_failures: &[], + }, + GeneratedBoundaryTestCase { + description: "Snowflake", + syntax: dialect_lexical_syntax("snowflake"), + expected_failures: &[], + }, + GeneratedBoundaryTestCase { + description: "ClickHouse", + syntax: dialect_lexical_syntax("clickhouse"), + expected_failures: &[], + }, + GeneratedBoundaryTestCase { + description: "the ClickHouse adapter's prefixes", + syntax: LexicalSyntax { + line_comment_prefixes: vec!["--".into(), "#".into(), "//".into()], + ..dialect_lexical_syntax("clickhouse") + }, + expected_failures: &[], + }, + GeneratedBoundaryTestCase { + description: "Databricks", + syntax: dialect_lexical_syntax("databricks"), + expected_failures: &[], + }, + GeneratedBoundaryTestCase { + description: "T-SQL", + syntax: dialect_lexical_syntax("tsql"), + expected_failures: &[], + }, + ]; + for test_case in test_cases { + let failures: Vec = generated_failures(&test_case.syntax); + assert_eq!( + failures.iter().take(12).collect::>(), + test_case.expected_failures.iter().collect::>(), + "{}: {} failures", + test_case.description, + failures.len() + ); + } +} + +#[test] +fn given_a_boundary_when_bounded_then_only_a_space_or_newline_is_added() { + let test_cases = [ + BoundaryTestCase { + description: "a negative after a minus", + template: "select -{} as x, 7 as y", + values: &["-1"], + dialect: "duckdb", + expected_sql: "select - -1 as x, 7 as y", + }, + BoundaryTestCase { + description: "a trailing comment before code", + template: "select {} as x, 7 as y", + values: &["1 -- one"], + dialect: "duckdb", + expected_sql: "select 1 -- one\n as x, 7 as y", + }, + BoundaryTestCase { + description: "an empty expansion between two halves", + template: "select a/{}*2", + values: &[""], + dialect: "duckdb", + expected_sql: "select a/ *2", + }, + BoundaryTestCase { + description: "a join", + template: "select {}_count", + values: &["orders"], + dialect: "duckdb", + expected_sql: "select orders_count", + }, + BoundaryTestCase { + description: "sites inside a string and a comment stay as they are", + template: "select '-{}' -- -{}", + values: &["-1", "-1"], + dialect: "duckdb", + expected_sql: "select '--1' -- --1", + }, + BoundaryTestCase { + description: "a slash pair is a comment on Snowflake", + template: "select a/{}", + values: &["/b"], + dialect: "snowflake", + expected_sql: "select a/ /b", + }, + BoundaryTestCase { + description: "a slash pair is not a comment on PostgreSQL", + template: "select a/{}", + values: &["/b"], + dialect: "postgres", + expected_sql: "select a//b", + }, + BoundaryTestCase { + description: "an unclosed block comment is left alone", + template: "select {} as x", + values: &["1 /* one"], + dialect: "duckdb", + expected_sql: "select 1 /* one as x", + }, + ]; + for test_case in test_cases { + let syntax: LexicalSyntax = dialect_lexical_syntax(test_case.dialect); + let (_, bounded) = spliced(test_case.template, test_case.values, &syntax); + assert_eq!(bounded, test_case.expected_sql, "{}", test_case.description); + } +} diff --git a/crates/sqlbuild-sqltext/src/sql_scan/tests/test_types.rs b/crates/sqlbuild-sqltext/src/sql_scan/tests/test_types.rs index 42ebb866b3..75e1829cc8 100644 --- a/crates/sqlbuild-sqltext/src/sql_scan/tests/test_types.rs +++ b/crates/sqlbuild-sqltext/src/sql_scan/tests/test_types.rs @@ -64,3 +64,19 @@ pub(crate) struct PrefixCheckTestCase { pub(crate) declared: &'static [&'static str], pub(crate) expected_unsupported: &'static [&'static str], } + +pub(crate) struct BoundaryTestCase { + pub(crate) description: &'static str, + /// `{}` marks each site. + pub(crate) template: &'static str, + pub(crate) values: &'static [&'static str], + pub(crate) dialect: &'static str, + pub(crate) expected_sql: &'static str, +} + +pub(crate) struct GeneratedBoundaryTestCase { + pub(crate) description: &'static str, + pub(crate) syntax: LexicalSyntax, + /// Splices that gained or lost code, or changed although they read right. + pub(crate) expected_failures: &'static [&'static str], +} diff --git a/deploy/Dockerfile b/deploy/Dockerfile index f07f0561cd..a9e050a04b 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -28,7 +28,12 @@ COPY --chown=10001:10001 deploy/project/ /project/ FROM docker.io/library/debian:bookworm-slim AS server RUN apt-get update && apt-get install --no-install-recommends -y ca-certificates curl \ && rm -rf /var/lib/apt/lists/* \ - && useradd --uid 10001 --create-home sqlbuild + && useradd --uid 10001 --create-home sqlbuild \ + && install --directory --owner=10001 --group=10001 \ + /home/sqlbuild/.local \ + /home/sqlbuild/.local/state \ + /home/sqlbuild/.local/state/sqlbuild \ + /home/sqlbuild/.local/state/sqlbuild/output COPY --from=runtime /usr/local/bin/sqb /usr/local/bin/sqb USER 10001:10001 ENTRYPOINT ["sqb"] diff --git a/deploy/README.md b/deploy/README.md index 402ed32e28..87153aeb20 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -53,20 +53,23 @@ direct-store administration path, not an HTTP or person-role grant: docker compose run --rm --no-deps server admin create-location orders ``` +It prints `Registered location orders ()`. + The server reads `/etc/sqlbuild/server.toml`, which `compose.yml` writes from its `server` config. Its `[[launchers.docker]]` entry starts workers for the location named `orders`, so create the location before the server starts. Edit that config and recreate the server to change launchers, retention or sign-in; see `sqb server` in the documentation for every setting. -Replace `.env`'s placeholder `SQLBUILD_LOCATION_ID` with the returned `location_id`. Issue a +Replace `.env`'s placeholder `SQLBUILD_LOCATION_ID` with that ID. Issue a bounded credential, using a future RFC 3339 expiry you choose: ```sh -docker compose run --rm --no-deps server admin issue-location-token "$SQLBUILD_LOCATION_ID" --expires-at "$EXPIRY" +SQLBUILD_LOCATION_TOKEN="$(docker compose run --rm --no-deps -T server admin issue-location-token "$SQLBUILD_LOCATION_ID" --expires-at "$EXPIRY")" ``` Shell variables above must be set explicitly; Compose's `.env` file is not sourced by the shell. -Store the one-time `bearer` in `.env` as `SQLBUILD_LOCATION_TOKEN`, restrict the file to its owner +The command prints the one-time bearer alone on stdout and what it did on stderr; `-T` keeps the +two apart. Store it in `.env` as `SQLBUILD_LOCATION_TOKEN`, restrict the file to its owner (`chmod 600 .env`), and start the stack: ```sh @@ -78,7 +81,10 @@ The location watches and compiles its baked project, publishes a successful snap its warehouse connection. The example schedule runs every minute. The server resolves the running container's actual Docker image ID at publication; no `--image-id` or Docker socket is needed in the location. Workers recompile in that pinned image and verify environment and node -hashes before writing. The warehouse persists in its named volume. +hashes before writing. The warehouse persists in its named volume, and so does run output: the +`output` volume is mounted at `/home/sqlbuild/.local/state/sqlbuild/output`, the server's default output +folder with PostgreSQL in this image, so recreating the server keeps it. `docker compose down +--volumes` deletes both. Check the location the way a container health check would; it exits 1 when the location is down or its last load failed: @@ -219,6 +225,7 @@ Network=sqlbuild.network PublishPort=127.0.0.1:8000:8000 Volume=/etc/sqlbuild/server.toml:/etc/sqlbuild/server.toml:ro Volume=/run/podman/podman.sock:/var/run/docker.sock +Volume=sqlbuild-output:/home/sqlbuild/.local/state/sqlbuild/output GroupAdd=993 SecurityLabelDisable=true Secret=sqlbuild-control-database-url,type=env,target=SQLBUILD_CONTROL_DATABASE_URL @@ -235,7 +242,7 @@ WantedBy=multi-user.target ``` `/etc/containers/systemd/orders-location.container`, with the `location_id` that -`create-location` returned: +`create-location` printed: ```ini [Unit] @@ -279,12 +286,14 @@ sudo podman healthcheck run orders-location so a server restart leaves it running; it checks in again when the server is back. - The server resolves launcher locations when it starts. To add a location, create it, add its launcher and container unit, then restart the server: `sudo systemctl restart sqlbuild-server`. +- The `sqlbuild-output` volume keeps run output when the server's container is recreated. Podman + creates it on first use, owned by the image's user (10001). - `SecurityLabelDisable=true` lets the server use the socket on SELinux hosts. ## Credentials, identity, and platform events -Rotate a location credential with `docker compose run --rm --no-deps server admin rotate-token -TOKEN_UUID`, store its one-time replacement bearer, and recreate the location. The scope and +Rotate a location credential with `docker compose run --rm --no-deps -T server admin rotate-token +TOKEN_UUID`, store the one-time replacement bearer it prints on stdout, and recreate the location. The scope and expiry stay unchanged, and the old credential is revoked atomically. Service-account principal tokens are separate from location/run tokens. Person identities do not become machine bearers. @@ -302,8 +311,8 @@ person and role checks. `POST /api/auth/logout` revokes the session across repli resets and `grant-admin` revoke all of that person's browser sessions. The local control-store owner initializes the first installation administrator with -`sqb admin create-user NAME`, then provisions its password separately with -`sqb admin set-password PRINCIPAL_ID`. `create-user` works only while no person exists; once +`sqb admin create-user NAME`, which prints the new person's ID, then provisions its password +separately with `sqb admin set-password PRINCIPAL_ID`. `create-user` works only while no person exists; once anyone exists, use `grant-admin` instead. `create-principal` creates a role-free identity, not another administrator. With password, OIDC or trusted-proxy authentication, installation administrators use `POST /api/admin/people/{principal_id}` with a JSON action of `grant`, `revoke`, `disable`, diff --git a/fensu.toml b/fensu.toml index 31a7caa0b8..b3d2d34e49 100644 --- a/fensu.toml +++ b/fensu.toml @@ -47,6 +47,21 @@ modules = ["sqlbuild._native_host"] symbols = ["*"] reason = "Native code imports this module by path and reads its attributes by name." +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.python_nodes.main.discovered_result_json"] +symbols = ["discovered_result_json"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.python_nodes.main.read_discover_definition"] +symbols = ["read_discover_definition"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.python_nodes._helpers.discovered_results"] +symbols = ["item_dependency_refs"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + [[targets.python.dead_code.roots]] modules = ["sqlbuild.adapter.contract.classes.base_adapter"] symbols = ["BaseAdapter"] @@ -778,7 +793,12 @@ symbols = ["audit_evidence_scope"] reason = "Native code resolves these through the sqlbuild._native_host name table." [[targets.python.dead_code.roots]] -modules = ["sqlbuild.runtime.execution_limits.main._cancel_running_statements"] +modules = ["sqlbuild.runtime.execution_limits.main.statement_activity"] +symbols = ["statement_activity"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.runtime.execution_limits.main.cancel_running_statements"] symbols = ["cancel_running_statements"] reason = "Native code resolves these through the sqlbuild._native_host name table." @@ -1376,7 +1396,7 @@ paths = ["crates/sqlbuild-rules/src/custom_rule_cache/main/parse_custom_rule_cac reason = "Each reads its own cache format: the SQL rule cache checks its version and the build identity and returns findings by path, the custom-rule cache checks only its version, because its identities already include the build, and returns rules by code. Only the parse-and-filter shape is alike." [[dupes.allowlist]] -paths = ["crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/changed_builds.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_node_sql.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_operations.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/trigger_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/warehouse_metadata.rs"] +paths = ["crates/sqlbuild-orchestration/src/api/_helpers/resources/administrators.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/audit.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/changed_builds.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_location_work.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_node_sql.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_operations.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_republish.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/service_accounts.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/trigger_reads.rs", "crates/sqlbuild-orchestration/src/api/_helpers/resources/warehouse_metadata.rs"] reason = "Each function is one utoipa-annotated axum route: OpenAPI needs one annotated handler per operation, and each body only checks the caller's scope and calls one store operation. Scope checks and store work live in their shared owners." [[dupes.allowlist]] @@ -1531,6 +1551,21 @@ path = "src/sqlbuild/assets.py" symbols = ["asset"] reason = "Bare @asset is evaluated by Python as asset(function), requiring positional function calling." +[[targets.python.rule_exceptions]] +rule = "FFS010" +path = "src/sqlbuild/assets.py" +symbols = ["asset"] +reason = "@asset's keywords are its public authoring API; for_each (CHI-1621) is the eleventh, and grouping them would change every project." +[[targets.python.rule_exceptions]] +rule = "FFS010" +path = "src/sqlbuild/python_nodes/main/apply_asset.py" +symbols = ["apply_asset"] +reason = "apply_asset takes @asset's public keywords one for one, so both signatures stay readable side by side." +[[targets.python.rule_exceptions]] +rule = "FFS120" +path = "src/sqlbuild/discovery.py" +symbols = ["discover"] +reason = "Bare @discover is evaluated by Python as discover(function), requiring positional function calling." [[targets.python.rule_exceptions]] rule = "FFS120" path = "src/sqlbuild/hooks.py" @@ -1750,6 +1785,12 @@ exceptions = [ "UsageKind=Wire enum that serde builds from Python usage records.", ] +[[targets.rust.rule_exceptions]] +rule = "FPRSS201" +path = "crates/sqlbuild-orchestration/src/credentials/models.rs" +symbols = ["IssuedServiceKey", "NewServiceKey"] +reason = "They implement Debug manually so a debug print never shows the service account key they carry; other models derive it." + [[targets.rust.rule_exceptions]] rule = "FPRSS201" path = "crates/sqlbuild-python-base/src/compile_context/models.rs" @@ -1955,11 +1996,23 @@ path = "crates/sqlbuild-orchestration/src/api/_helpers/resources/plain_http.rs" symbols = ["warn_plain_http"] reason = "Locations, workers and remote publication share this client; it warns once per process on stderr, before any request, when a bearer token would travel over plain HTTP to a non-loopback host." +[[targets.rust.rule_exceptions]] +rule = "FPRSS130" +path = "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/audit_repeats.rs" +symbols = ["audit_due", "record_audit"] +reason = "A page following a run repeats its output reads every few seconds; this process-wide record of when each person last had each kind of read of each run audited lets the server audit those reads once per window rather than writing an audit row per poll. Authorization still runs on every read." + +[[targets.rust.rule_exceptions]] +rule = "FPRSH011" +path = "crates/sqlbuild-orchestration/src/run_output/_helpers/prune.rs" +symbols = ["report_retention_failure"] +reason = "Output retention runs in the server's maintenance role, which has no caller to return a failure to without stopping the other retention policies; the operator reads on stderr which run's output could not be removed, and it is retried on the next pass." + [[targets.rust.rule_exceptions]] rule = "FPRSH011" path = "crates/sqlbuild-orchestration/src/api/_helpers/authentication/proxy_warnings.rs" -symbols = ["warn_plain_http_origin", "warn_untrusted_source", "warn_untrusted_overflow", "warn_taken_username", "warn_refused_host"] -reason = "The server's operator reads trusted-proxy misconfiguration on stderr: a plain-HTTP origin at start-up, and once each the untrusted peers that send the username header, the usernames refused because another principal holds the name, and the escaped Host values a trusted peer was refused under, so they can be added to allowed_hosts. Untrusted peers' header values are never printed." +symbols = ["warn_plain_http_origin", "warn_plain_http_keys", "warn_untrusted_source", "warn_untrusted_overflow", "warn_taken_username", "warn_refused_host"] +reason = "The server's operator reads sign-in misconfiguration on stderr: a plain-HTTP origin, or service keys accepted on a network listener without an https:// origin, at start-up, and once each the untrusted peers that send the username header, the usernames refused because another principal holds the name, and the escaped Host values a trusted peer was refused under, so they can be added to allowed_hosts. Untrusted peers' header values are never printed." [[targets.rust.rule_exceptions]] rule = "FPRSS201" @@ -3197,6 +3250,7 @@ module_layers = [ "microbatches=registry", "model_config=registry", "native_host=front", + "native_host/discover_runner=commands", "native_host/live_reads=plan", "native_host/orchestration_sensors=commands", "native_host/setup_context=commands", @@ -4060,3 +4114,37 @@ reason = "One reads the active location with a name, the other the development l [[dupes.allowlist]] paths = ["crates/sqlbuild-python-compile/src/rules/_helpers/sql/sql_test_objects.rs", "crates/sqlbuild-python-front/src/discovery/_helpers/project/project_facts.rs"] reason = "Each parses one closed string set into its own enum: SQL test modes, directly tested resource kinds, and Python node kinds. Only the match-or-ValueError shape is alike." + +[[dupes.allowlist]] +paths = ["crates/sqlbuild-orchestration/src/declarations/main/published_job.rs", "crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs", "crates/sqlbuild-orchestration/src/snapshots/main/reads/read_current_record.rs"] +reason = "Each reads at most one row of its own table by its own key: a published job, one stream of a run's output, the current snapshot record. Only the query-then-take-the-first shape is alike." + +[[dupes.allowlist]] +paths = ["crates/sqlbuild-orchestration/src/run_output/_helpers/index.rs", "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs", "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/node_runs.rs"] +reason = "Each lists its own rows for one run: the output segments holding a line range, check results, node runs. Only the keyed query_records call is alike." + +[[dupes.allowlist]] +paths = ["crates/sqlbuild-python-base/src/compile_context/_helpers/input_reads.rs", "crates/sqlbuild-python-base/src/event_exporting/_helpers/scope.rs", "crates/sqlbuild-python-output/src/output_capture/main/register_context.rs"] +reason = "Each registers its own module's Python classes and functions; only the add-class and add-function calls are alike." + +[[dupes.allowlist]] +paths = ["src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py", "src/sqlbuild/executor/python_nodes/classes/read_side_python_execution_tracker.py"] +reason = "Each finalizes a successful Python node for its own executor, ingress callbacks or the read-side tracker, which own different result stores and identity recorders. Only the scope-and-fingerprint shape is alike." + +[[dupes.allowlist]] +paths = ["scripts/compiler_differential/classes/discovery_features.py"] +reason = "Each method writes one discovery feature's own fixture files for the compiler differential; only the write-files shape is alike." + +[[targets.rust.rule_exceptions]] +rule = "FPRSS130" +path = "crates/sqlbuild-orchestration/src/run_output/_helpers/upload.rs" +symbols = ["attached"] +reason = "A worker process runs one run, and the bytes it prints reach the uploader through the process-wide output capture, which has no handle to the worker; the uploader is attached once when the run starts and taken once when it finishes." + +[[dupes.allowlist]] +paths = ["crates/sqlbuild-analysis/src/sql_tokens/main/normalized_query_text.rs", "crates/sqlbuild-cache/src/digest/_helpers/distributions.rs", "crates/sqlbuild-cli/src/argv/_helpers/text_wrap.rs", "crates/sqlbuild-orchestration/src/run_output/_helpers/chunks.rs"] +reason = "Each collapses runs of one character class into a single marker for its own purpose: whitespace in query text, distribution keys and wrapped help text, digits in printed lines so similar lines fold. They live in crates that do not depend on each other; only the run-collapsing loop is alike." + +[[dupes.allowlist]] +paths = ["crates/sqlbuild-orchestration/src/declarations/_helpers/reads.rs", "crates/sqlbuild-orchestration/src/run_output/_helpers/views.rs", "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs"] +reason = "Each lists its own rows by its own key: triggers, latest ticks, a node's output marks and latest check results. Only the keyed query_records call is alike." diff --git a/python-boundary.toml b/python-boundary.toml index 24e44705c5..fa8ac7a43d 100644 --- a/python-boundary.toml +++ b/python-boundary.toml @@ -592,6 +592,11 @@ path = "assets.py" rule = 3 note = "Public facade: re-exports plus one-line delegating wrappers (asset, get_asset_definition)." +[[stays]] +path = "discovery.py" +rule = 3 +note = "Public facade: re-exports plus one-line delegating wrappers (discover, get_discover_definition)." + [[stays]] path = "audits.py" rule = 3 diff --git a/scripts/compiler_differential/classes/discovery_features.py b/scripts/compiler_differential/classes/discovery_features.py index e26eb7c34a..e53f299d5d 100644 --- a/scripts/compiler_differential/classes/discovery_features.py +++ b/scripts/compiler_differential/classes/discovery_features.py @@ -90,6 +90,7 @@ def write(self) -> None: "python_hook": self._python_hook, "managed_source_loader": self._managed_source_loader, "asset_and_check": self._asset_and_check, + "discovered_set": self._discovered_set, "audit_factory": self._audit_factory, "provider": self._provider, "lifecycle_sink": self._lifecycle_sink, @@ -179,7 +180,7 @@ def _python_hook(self) -> None: "@hook\n" 'def note_refresh(ctx, channel="#builds"):\n' ' """Log one refresh."""\n' - ' ctx.log(f"{channel}: {ctx.model_name} refreshed during {ctx.phase}")\n' + ' ctx.log.info(f"{channel}: {ctx.model_name} refreshed during {ctx.phase}")\n' ) _ = self._model( name=f"hooked_{base.name}", @@ -234,6 +235,25 @@ def _asset_and_check(self) -> None: " return ctx.pass_()\n" ) + def _discovered_set(self) -> None: + self._features.add("discovered_set") + self._files["python/assets/steps.py"] = ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.discovery import Discovered, Item, discover\n\n\n" + '@discover(check_every="60s")\n' + "def step_plan():\n" + ' """List the steps of an external plan; only a location calls this."""\n' + " return Discovered(\n" + ' items=(Item(id="load", args={"step": "load"}), ' + 'Item(id="fit", depends_on=("load",), args={"step": "fit"})),\n' + ' tags={"release": "r1"},\n' + " )\n\n\n" + '@asset(for_each=step_plan, tags=("steps",))\n' + "def run_step(ctx, step):\n" + ' """Run one discovered step."""\n' + ' return ctx.result(metadata={"step": step}, materialized=True)\n' + ) + def _audit_factory(self) -> None: self._features.add("audit_factory") base: ModelPlan = self._base() diff --git a/scripts/compiler_differential/constants.py b/scripts/compiler_differential/constants.py index 8b831998b9..813d642d4e 100644 --- a/scripts/compiler_differential/constants.py +++ b/scripts/compiler_differential/constants.py @@ -264,6 +264,7 @@ def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: "line_endings", *GENERATOR_RENDER_BLOCKS, *GENERATOR_ANALYSIS_BLOCKS, + "discovered_set", ) GENERATOR_FEATURE_STRIDE: int = 4 GENERATOR_OPTIONAL_FEATURE_SHARE: float = 0.2 diff --git a/scripts/setting_help/_helpers/scan.py b/scripts/setting_help/_helpers/scan.py index 863070a269..39df964013 100644 --- a/scripts/setting_help/_helpers/scan.py +++ b/scripts/setting_help/_helpers/scan.py @@ -3,12 +3,13 @@ from __future__ import annotations import ast +from collections.abc import Iterator from pathlib import Path from scripts.setting_help.constants import ( DOTTED_SETTING_INSTRUCTION_PATTERN, - RUST_STRING_DELIMITER, RUST_TEST_PATH_MARKER, + RUST_TOKEN_PATTERN, YAML_FILE_TEXT_MODULES, YAML_STYLE_SETTING_PATTERN, ) @@ -34,12 +35,25 @@ def rust_findings(repository_root: Path) -> list[str]: relative: str = path.relative_to(repository_root).as_posix() if RUST_TEST_PATH_MARKER in relative or relative in YAML_FILE_TEXT_MODULES: continue - for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): - if RUST_STRING_DELIMITER in line and names_setting_without_snippet(line): - findings.append(f"{relative}:{number}: {line.strip()}") + source: str = path.read_text(encoding="utf-8") + lines: list[str] = source.splitlines() + for number, literal in rust_string_literals(source): + if names_setting_without_snippet(literal): + findings.append(f"{relative}:{number}: {lines[number - 1].strip()}") return findings +def rust_string_literals(source: str) -> Iterator[tuple[int, str]]: + """Each string literal's line and text, skipping comments, char literals and lifetimes.""" + + for token in RUST_TOKEN_PATTERN.finditer(source): + text: str | None = ( + token.group("raw") if token.group("raw") is not None else token.group("text") + ) + if text is not None: + yield source.count("\n", 0, token.start()) + 1, text + + def names_setting_without_snippet(text: str) -> bool: return bool( YAML_STYLE_SETTING_PATTERN.search(text) or DOTTED_SETTING_INSTRUCTION_PATTERN.search(text) diff --git a/scripts/setting_help/constants.py b/scripts/setting_help/constants.py index 1b33022ae7..46e2dc560e 100644 --- a/scripts/setting_help/constants.py +++ b/scripts/setting_help/constants.py @@ -22,4 +22,11 @@ } ) RUST_TEST_PATH_MARKER: str = "/tests/" -RUST_STRING_DELIMITER: str = '"' +RUST_TOKEN_PATTERN: re.Pattern[str] = re.compile( + r"//[^\n]*" + r"|/\*.*?\*/" + r'|(?#*)"(?P.*?)"(?P=hashes)' + r'|(?(?:\\.|[^"\\])*)"' + r"|(? + +# Discovered nodes + +> Run a Python asset once per item an external system lists, with @discover and @asset(for_each=...). + +Online: https://sqlbuild.com/docs/concepts/python-nodes/discovered-nodes/ + +## Contents + +- Declaring a discovered set +- Dependencies +- In a node +- Selecting discovered nodes +- Running items in parallel +- When discovery runs +- When discovery fails +- Outside a location +- Details + +A discover function asks an external system which items exist, and an asset with `for_each` runs once per item. The location calls the function when it publishes and saves its result in the snapshot, so every run executes exactly the nodes it published. + +```python +# python/fulfilment/nodes.py +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import model + +@discover(check_every="15m") +def fulfilment_plan(warehouse_api) -> Discovered: + """Steps of today's fulfilment plan.""" + plan = warehouse_api.todays_plan() + return Discovered( + items=[ + Item(id=step["id"], depends_on=step["after"], args={"region": step["region"]}) + for step in plan["steps"] + ], + tags={"plan_version": plan["version"]}, + max_parallel=4, + ) + +@asset(for_each=fulfilment_plan, depends_on=model("orders")) +def fulfil(ctx: AssetContext, region: str) -> None: + """Run one step of the plan.""" + ctx.log.info(f"step {ctx.discovered.item} for {region}, plan {ctx.discovered.tags['plan_version']}") +``` + +With steps `pick`, `pack` and `ship`, where each waits on the one before, the graph is +`orders → fulfil[pick] → fulfil[pack] → fulfil[ship]`. + +## Declaring a discovered set + +- **`@discover`** marks a project function under `python/` that returns `Discovered`. Providers are injected by parameter name, as for any Python node. Pass `name=` to name the set something other than the function, and `check_every=` to have the location check it for changes (see [When discovery runs](#when-discovery-runs)). +- **`Discovered`** is the only return form: `items`, plus optional set-wide `tags` and `max_parallel`. +- **`Item`** has an `id`, a `depends_on` and `args`. + - `id` is unique in the set, at most 200 characters, and uses only letters, digits and `_ . : -`. + - `depends_on` lists the IDs of other items of the set. It may also name project nodes with `model()`, `source()`, `seed()`, `job()` or `tag()`. + - `args` fill the asset function's own parameters, other than its context and providers. +- **`@asset(for_each=...)`** names the discover function. It is an ordinary Python asset: it takes every other `@asset` parameter, and one discover function may feed several assets. Each item becomes one node per asset, named `[]`. + +A set fails as a whole, and keeps its last good items, when: + +- the function raises or returns something other than `Discovered`; +- it returns no items, as an empty answer from a remote system is far more often a fault than a plan with no steps; +- an ID is invalid or repeated, an item depends on an ID outside the set, or items depend on each other in a cycle; +- an item depends on a model, source, seed or job the project doesn't have; +- an item's `args` name a parameter the asset doesn't have, or leave a parameter without a default unset; +- `args` or `tags` aren't JSON data. + +## Dependencies + +- The asset's own `depends_on` attaches to the set's **roots**, the items that wait on no other item of the set. Every other item waits on a root, so ordering is exact. +- Other nodes depend on the set with `job()` or `tag()`, which resolve to its last nodes. Nothing needs to name an item. + +## In a node + +| Attribute | Description | +|-----------|-------------| +| `ctx.discovered.item` | The item ID this node runs for | +| `ctx.discovered.set` | The discover function's name | +| `ctx.discovered.tags` | The set's tags, as saved at publish | +| `ctx.root_run_id` | The server's run ID of the first run in the rerun chain. Reruns and automatic retries keep it, so an external pipeline can keep one identity across them. Don't compare it with `ctx.run_id`, which is the worker's own ID and differs on every run. Outside a worker it is the local run's ID | + +`ctx.discovered` is `None` for an asset without `for_each`. + +## Selecting discovered nodes + +| Selector | Selects | +|----------|---------| +| `fulfil[pack]` | The one node of item `pack` | +| `+fulfil[ship]` | Item `ship` and every item and node before it | +| `fulfil` or `asset:fulfil` | Every node of the asset, whatever the items are | + +Jobs select the asset by name, so job files don't change when the items do. + +## Running items in parallel + +`max_parallel` caps how many of the set's nodes run at once within one run. Assets fed by the same +discover function share the cap. Without it, or with `1`, the items run one at a time. It is +independent of `concurrency`, and every other asset still runs one at a time. + +- **Providers used by these steps must be thread-safe.** The steps run on threads of one process and share the provider instances. +- **A step can't install signal handlers,** as Python allows that only on the main thread. +- **Each running step has its own warehouse connection.** An in-memory DuckDB, MotherDuck or SQLite database belongs to one connection, so on those targets items run one at a time, whatever `max_parallel` is. Use a database file to run them in parallel. +- **Local output can interleave.** A worker still files each line under the node that printed it. +- **SQL pauses while items run.** New SQL, and steps waiting on SQL, start again once the running items have finished. +- **A cancel starts no more steps.** It cancels running statements and keeps finished steps succeeded. SQLBuild can't stop other Python code, so it waits 5 seconds for those steps, then records them cancelled and exits. It doesn't tear down providers that such a step may still be using: their `teardown` doesn't run. Work a step started on a remote system may outlive the cancel. + +## When discovery runs + +Only a location, including `sqb dev`, calls discover functions. Every other compile uses the result saved in the snapshot, like a lockfile: + +| Trigger | What happens | +|---------|--------------| +| The location starts (every deploy or restart) | Every discover function runs | +| `r` in `sqb dev` | Every discover function runs, and the location publishes | +| A [republish](../../cli/location.md#republish), from the UI, the CLI or the API | Every discover function runs, and the location publishes | +| A saved project file | The location publishes and reuses the saved sets; a discover function runs again only when its own module changed | +| `check_every` | The location calls that function without publishing. When the result differs from the saved set, it publishes with the new result | + +- `check_every` takes amounts in `d`, `h`, `m` and `s`, largest unit first, such as `15m` or `1h30m`, and at least a minute. Without it, the set is checked only when the location publishes. +- A check doesn't hold up the location. Once a publish, republish or other request waits for it, the check has 10 seconds to finish. After that the location restarts its interpreter and serves the request, and the set is checked again when it is next due. +- Runs always execute the nodes of the snapshot they started on. Workers, reruns and the plan page never call discover functions. +- `sqb dev`'s ready card shows the sets, for example `Discovered fulfilment_plan 3 items`. + +## When discovery fails + +- **A set fails on its own.** It keeps its last good items, the location's health shows **Discovery failed** with the set and its error, and everything else publishes normally. A location that restarts reads the last good items from the server's current snapshot. +- **Last good items that name a model, source, seed or job the project no longer has** aren't kept. That covers a publish that reuses a set after the model it names was renamed or removed: the set fails with an error naming the item and the missing node, and compiles as its placeholder until it's discovered again. +- **An item that depends on a `tag()` no node carries** still fails the whole publish, not only its set: tags are known only once the project compiles. The location keeps its current snapshot and reports the error. +- **A set that never succeeded** compiles as its **placeholder node**, `[*]`. Its `job()` and `tag()` dependants stay valid. A run that reaches it fails that node with `never discovered: `, and its downstream nodes are skipped. + +## Outside a location + +`sqb compile`, `sqb plan` and `sqb build` never call discover functions by default. Each `for_each` asset compiles as its placeholder, `fulfil[*]`, so lineage and `job()`/`tag()` dependencies stay valid. + +Selecting a placeholder to run fails: + +```text +error[S000]: fulfil is discovered at publish; run it from a location or `sqb dev`, or pass --discover +``` + +Pass `--discover` to run the discover functions for that one command, with the selected target's providers: + +```bash +sqb build --discover --select +fulfil[ship] +``` + +Nothing is written to disk. If a discover function fails under `--discover`, the command stops with its error. + +## Details + +- Discovered nodes are Python assets only; discovery returns data, never code. +- To create several sets from one source, use a [factory](factories.md) that returns one discover function and one asset per set. +- A node's identity includes its item's `args` and the set's `tags`, so a changed argument shows in the plan like a code change. +- Workers compile the saved sets of the run's snapshot, so a run is unaffected by changes in the external system after it was published. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md index bcd5033ee0..ed44768bec 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/loaders.md @@ -271,7 +271,7 @@ Every loader function receives a `LoaderContext` as its first argument. It provi |--------|-------------| | `execute_sql(sql)` | Execute a SQL statement against the connection | | `query(sql)` | Execute a SQL query and return the cursor | -| `log(message)` | Log a message to the execution lifecycle output | +| `log.info(message)`, `log.warning(message)`, `log.error(message)` | Log a line at that level; it shows with the run's events, while anything the loader prints stays its output | | `qualify_name(name)` | Return a fully-qualified relation name in the destination database/schema | | `skip(reason, mode=...)` | Skip this loader. `mode` is `"soft"` (default, skip only this loader) or `"hard"` (also block dependents) | | `result(payload=, metadata=, materialized=)` | Return a structured result for a self-managed loader | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md index 5df4e8c8ba..43d0543a09 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/overview.md @@ -152,13 +152,13 @@ Each node receives a context object as its first argument (`AssetContext`, `Chec | Helper | Description | |--------|-------------| -| `ctx.run_id` | Unique identifier for this run | +| `ctx.run_id` | Unique identifier for this run; in a worker, the worker's own ID rather than the server's run ID | | `ctx.target` | Active target name | | `ctx.target_config` | The active target's database and schemas, as SQLBuild resolves them (see [Target settings](#target-settings)) | | `ctx.vars` | Project variables | | `ctx.is_reload` | `True` when `--reload` was passed | | `ctx.adapter` / `ctx.connection` | Adapter and live connection | -| `ctx.log(message)` | Log to the run output | +| `ctx.log.info(message)`, `ctx.log.warning(message)`, `ctx.log.error(message)` | Log a line at that level; it shows with the run's events, while anything the node prints stays its output | | `ctx.query(sql)` / `ctx.execute_sql(sql)` | Run SQL on the connection | | `ctx.qualify_name(name)` | Qualify a relation name | | `ctx.relation(ref)` | Resolve a declared `model()`/`source()` reference to a relation | @@ -166,7 +166,7 @@ Each node receives a context object as its first argument (`AssetContext`, `Chec | `ctx.results_of(node_fn, limit=N)` | Read the last N successful results of an upstream node, newest first | | `ctx.providers` | Access discovered [providers](providers.md) by name | -Asset contexts add `ctx.result(...)` and `ctx.skip(...)`. Check contexts add `ctx.pass_(...)`, `ctx.fail(...)`, and `ctx.warn(...)`. +Asset contexts add `ctx.result(...)`, `ctx.skip(...)`, `ctx.root_run_id` and `ctx.discovered` (see [Discovered nodes](discovered-nodes.md#in-a-node)). Check contexts add `ctx.pass_(...)`, `ctx.fail(...)`, and `ctx.warn(...)`. Providers can also be injected directly as function parameters by name. See [Providers](providers.md) for details. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md index b26a570ee5..2a3797646f 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/python-nodes/providers.md @@ -152,7 +152,7 @@ Providers follow a lazy setup, reverse-teardown lifecycle scoped to the command 1. **Discovery** - on compile, SQLBuild discovers all `Provider` subclasses under `providers/` and validates their settings (from environment variables or field defaults). Missing [secrets](#secrets) follow the command's rules. 2. **Lazy setup** - the first time a provider is accessed during a build, SQLBuild reads its settings and calls `setup(ctx)`. Providers that are never used are never set up. -3. **Teardown** - after the command completes, `teardown()` is called on all providers that were set up, in reverse setup order. Teardown runs even if the build failed. +3. **Teardown** - after the command completes, `teardown()` is called on all providers that were set up, in reverse setup order. Teardown runs even if the build failed. The exception is a cancel that leaves a step with `max_parallel` running after 5 seconds: providers are then not torn down, as that step may still use them (see [Running items in parallel](discovered-nodes.md#running-items-in-parallel)). ```python class WarehouseClient(Provider): @@ -233,6 +233,11 @@ class SlackAlerts(Provider): slack_webhook_url: SecretStr # reads SLACK_WEBHOOK_URL ``` +Declare every secret a provider needs as a required field. Don't declare it as optional, such as +`api_key: SecretStr | None = None`, and fail in `setup` or in a method when it is empty: SQLBuild +can't know that such a field is required, so none of the checks below see it, and a run fails only +when its node first uses the provider, after connecting and planning. + SQLBuild looks for each variable in the environment and then in the project's [env file](../project-configuration.md#env-file). @@ -248,9 +253,12 @@ SQLBuild looks for each variable in the environment and then in the project's ```text $ sqb compile error[D012]: provider 'slack_alerts' (providers/slack_alerts/provider.py) is missing secret SLACK_WEBHOOK_URL - = help: set SLACK_WEBHOOK_URL, or pass --allow-missing-secrets where secrets aren't available + = help: set SLACK_WEBHOOK_URL in this shell or in .env, or pass --allow-missing-secrets where secrets aren't available ``` +The help names the env file the selected target loads, and suggests the flag only on the commands +that take it. + A run names each variable, the nodes that use the provider and the selected nodes that read them, and where it looked: @@ -259,7 +267,7 @@ $ sqb build --select +partner_orders_report error[D012]: selected nodes need secrets that are missing from the environment and from .env: partner_api PARTNER_API_TOKEN (raw_partner_orders; read by partner_orders_report) nothing was run - = help: set each variable in this shell or the project's env file, or narrow the selection + = help: set each variable in this shell or in .env, or narrow the selection ``` Run [`sqb debug`](../../cli/debug.md) to see which secrets this machine has. @@ -314,7 +322,9 @@ In `--json`, `cant_run` names the sink under `sinks`. Nobody looks at a plan for a schedule or sensor, so its run checks the same thing on the worker, before compiling a plan or connecting. Each node that uses the provider fails with `D012`, the nodes that read it are skipped, and the run page shows **Couldn't run** with the provider, its variables -and the fix: set them in the location's environment or its env file, and restart the location. +and the fix: set them in the location's env file, or in the environment the location was started +with, then restart the location. Under `sqb dev`, `r` is enough after editing the env file; a +change to the environment needs `sqb dev` to be started again. The location reports the providers missing secrets each time it publishes. Its page lists them with their variables, fields and the nodes that can't run, and the Overview lists the problem for that diff --git a/src/sqlbuild/_native.pyi b/src/sqlbuild/_native.pyi index fc5c5e3fc2..dfa2d5e7c5 100644 --- a/src/sqlbuild/_native.pyi +++ b/src/sqlbuild/_native.pyi @@ -2973,6 +2973,11 @@ class CommandOutputContext: def __enter__(self) -> None: ... def __exit__(self, *exc_info: object) -> bool: ... +class OutputNodeScope: + def __enter__(self) -> None: ... + def __exit__(self, *exc_info: object) -> bool: ... + +def output_node_scope(node_key: str, /) -> OutputNodeScope: ... def command_output_context(*, external_context: Mapping[str, object]) -> CommandOutputContext: ... def current_output_capture_context() -> OutputCaptureContext | None: ... def chunk_command_output_text(*, text: str, max_bytes: int) -> tuple[str, ...]: ... @@ -4405,6 +4410,7 @@ def scope_expected_model_names( def supports_color() -> bool: ... def parse_cli_invocation(argv: Sequence[str], *, use_color: bool) -> ParsedCliInvocation: ... def run_cli(argv: Sequence[str] | None = None, handlers: object | None = None) -> int: ... +def run_interruptible(run: Callable[[], int]) -> int: ... def termination_requested() -> bool: ... def scope_test_ctes( texts: list[tuple[str, str]], syntax: dict[str, object] @@ -4505,6 +4511,7 @@ def validated_model_cursor_intrinsics( *, sql: str, config_values: Mapping[str, object], model_name: str ) -> str: ... def cursor_intrinsics_analysis_sql(*, sql: str, cursor_type: object) -> str: ... +def replace_cursor_markers(*, sql: str, start_sql: str, end_sql: str) -> str: ... def resolve_cursor_intrinsics( *, sql: str, start_sql: str | None = None, end_sql: str | None = None ) -> tuple[str, bool]: ... @@ -10604,11 +10611,13 @@ class DiscoveredPythonAssetMetadata(NativeRecord): columns: tuple[SourceColumnEntry, ...] column_lineage: dict[str, tuple[ColumnLineageRef, ...]] | None retry: RetryPolicy | None + discovered: dict[str, object] | None def __init__( self, columns: tuple[SourceColumnEntry, ...] = ..., column_lineage: dict[str, tuple[ColumnLineageRef, ...]] | None = ..., retry: RetryPolicy | None = ..., + discovered: dict[str, object] | None = ..., ) -> None: ... class DiscoveredPythonCheckMetadata(NativeRecord): @@ -14992,6 +15001,8 @@ class DiscoveredAssetFunction(NativeRecord): retry: RetryPolicy | None provider_usages: tuple[DiscoveredProviderUsage, ...] identity: PythonNodeIdentity | None + for_each: str | None + discovered: dict[str, object] | None def __init__( self, file_path: Path, @@ -15008,6 +15019,27 @@ class DiscoveredAssetFunction(NativeRecord): retry: RetryPolicy | None = ..., provider_usages: tuple[DiscoveredProviderUsage, ...] = ..., identity: PythonNodeIdentity | None = ..., + for_each: str | None = ..., + discovered: dict[str, object] | None = ..., + ) -> None: ... + +class DiscoveredDiscoverFunction(NativeRecord): + """A discovered project function that discovers a set of items at publish.""" + + file_path: Path + relative_path: Path + name: str + function: Callable[..., object] + check_every_seconds: int | None + provider_usages: tuple[DiscoveredProviderUsage, ...] + def __init__( + self, + file_path: Path, + relative_path: Path, + name: str, + function: Callable[..., object], + check_every_seconds: int | None = ..., + provider_usages: tuple[DiscoveredProviderUsage, ...] = ..., ) -> None: ... class DiscoveredCheckFunction(NativeRecord): @@ -15189,12 +15221,16 @@ class DiscoveredPythonNodeFunctions(NativeRecord): assets: tuple[DiscoveredAssetFunction, ...] checks: tuple[DiscoveredCheckFunction, ...] audit_factories: tuple[DiscoveredAuditFactory, ...] + discover_functions: tuple[DiscoveredDiscoverFunction, ...] + for_each_assets: tuple[DiscoveredAssetFunction, ...] def __init__( self, loaders: tuple[DiscoveredLoaderFunction, ...] = ..., assets: tuple[DiscoveredAssetFunction, ...] = ..., checks: tuple[DiscoveredCheckFunction, ...] = ..., audit_factories: tuple[DiscoveredAuditFactory, ...] = ..., + discover_functions: tuple[DiscoveredDiscoverFunction, ...] = ..., + for_each_assets: tuple[DiscoveredAssetFunction, ...] = ..., ) -> None: ... class DiscoveredProjectInputs(NativeRecord): @@ -15221,6 +15257,8 @@ class DiscoveredProjectInputs(NativeRecord): loader_functions: tuple[DiscoveredLoaderFunction, ...] asset_functions: tuple[DiscoveredAssetFunction, ...] check_functions: tuple[DiscoveredCheckFunction, ...] + discover_functions: tuple[DiscoveredDiscoverFunction, ...] + for_each_assets: tuple[DiscoveredAssetFunction, ...] audit_factories: tuple[DiscoveredAuditFactory, ...] hook_functions: tuple[DiscoveredHookFunction, ...] event_exporters: tuple[DiscoveredEventExporter, ...] @@ -15251,6 +15289,8 @@ class DiscoveredProjectInputs(NativeRecord): loader_functions: tuple[DiscoveredLoaderFunction, ...] = ..., asset_functions: tuple[DiscoveredAssetFunction, ...] = ..., check_functions: tuple[DiscoveredCheckFunction, ...] = ..., + discover_functions: tuple[DiscoveredDiscoverFunction, ...] = ..., + for_each_assets: tuple[DiscoveredAssetFunction, ...] = ..., audit_factories: tuple[DiscoveredAuditFactory, ...] = ..., hook_functions: tuple[DiscoveredHookFunction, ...] = ..., event_exporters: tuple[DiscoveredEventExporter, ...] = ..., diff --git a/src/sqlbuild/_native_host.py b/src/sqlbuild/_native_host.py index cb5f16868c..808cd440c7 100644 --- a/src/sqlbuild/_native_host.py +++ b/src/sqlbuild/_native_host.py @@ -306,6 +306,18 @@ "sqlbuild.runtime.event_exporting.main._invoke_recall_sink", "invoke_recall_sink", ), + "read_discover_definition": ( + "sqlbuild.python_nodes.main.read_discover_definition", + "read_discover_definition", + ), + "discovered_result_json": ( + "sqlbuild.python_nodes.main.discovered_result_json", + "discovered_result_json", + ), + "item_dependency_refs": ( + "sqlbuild.python_nodes._helpers.discovered_results", + "item_dependency_refs", + ), "run_command_output_sinks": ( "sqlbuild.runtime.event_exporting.main._run_command_output_sinks", "run_command_output_sinks", @@ -595,9 +607,13 @@ "audit_evidence_scope", ), "cancel_running_statements": ( - "sqlbuild.runtime.execution_limits.main._cancel_running_statements", + "sqlbuild.runtime.execution_limits.main.cancel_running_statements", "cancel_running_statements", ), + "statement_activity": ( + "sqlbuild.runtime.execution_limits.main.statement_activity", + "statement_activity", + ), "EventDispatcher": ( "sqlbuild.runtime.observability.classes.event_dispatcher", "EventDispatcher", diff --git a/src/sqlbuild/_native_host.pyi b/src/sqlbuild/_native_host.pyi index e097d809de..38b2afd00e 100644 --- a/src/sqlbuild/_native_host.pyi +++ b/src/sqlbuild/_native_host.pyi @@ -543,7 +543,7 @@ from sqlbuild.runtime.execution_history.types import RunStatus as RunStatus from sqlbuild.runtime.execution_limits.exceptions import ( ExecutionDurationLimitError as ExecutionDurationLimitError, ) -from sqlbuild.runtime.execution_limits.main._cancel_running_statements import ( +from sqlbuild.runtime.execution_limits.main.cancel_running_statements import ( cancel_running_statements as cancel_running_statements, ) from sqlbuild.runtime.execution_limits.main.execution_deadline_scope import ( @@ -552,6 +552,9 @@ from sqlbuild.runtime.execution_limits.main.execution_deadline_scope import ( from sqlbuild.runtime.execution_limits.main.execution_deadlines_suspended import ( execution_deadlines_suspended as execution_deadlines_suspended, ) +from sqlbuild.runtime.execution_limits.main.statement_activity import ( + statement_activity as statement_activity, +) from sqlbuild.runtime.execution_limits.models import RunItemTimeouts as RunItemTimeouts from sqlbuild.runtime.observability.classes.event_dispatcher import ( EventDispatcher as EventDispatcher, diff --git a/src/sqlbuild/adapter/contract/classes/duckdb_backed_adapter.py b/src/sqlbuild/adapter/contract/classes/duckdb_backed_adapter.py index 42e2bc688f..04f60c8c95 100644 --- a/src/sqlbuild/adapter/contract/classes/duckdb_backed_adapter.py +++ b/src/sqlbuild/adapter/contract/classes/duckdb_backed_adapter.py @@ -133,6 +133,15 @@ def get_columns_for_relations( def create_table_as_replaces(self) -> bool: return True + def rebuilt_table_row_count( + self, *, connection: Any, database: str | None, schema: str | None, name: str + ) -> int | None: + """DuckDB's catalog size is exact right after a table is created; deletes leave it stale.""" + + return self.estimate_relation_row_count( + connection=connection, database=database, schema=schema, name=name, metadata_only=True + ).row_count + def create_sql_test_output(self, *, connection: Any, sql: str, name: str) -> str | None: """Store a unit test's output in a temporary table; compare inline on an engine bug.""" diff --git a/src/sqlbuild/adapter/contract/classes/node_logger.py b/src/sqlbuild/adapter/contract/classes/node_logger.py new file mode 100644 index 0000000000..e5caeb2d60 --- /dev/null +++ b/src/sqlbuild/adapter/contract/classes/node_logger.py @@ -0,0 +1,42 @@ +"""`ctx.log`: the few lines a node logs, kept with its run's events.""" + +from __future__ import annotations + +import logging + +from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder +from sqlbuild.adapter.contract.types import LogLevel + +_PYTHON_LEVELS: dict[LogLevel, int] = { + LogLevel.INFO: logging.INFO, + LogLevel.WARNING: logging.WARNING, + LogLevel.ERROR: logging.ERROR, +} + + +class NodeLogger: + """Log a line at info, warning or error; everything a node prints stays its output.""" + + def __init__(self, *, recorder: StatementRecorder, logger: logging.Logger | None) -> None: + self._recorder: StatementRecorder = recorder + self._logger: logging.Logger | None = logger + + def info(self, message: str) -> None: + """Log `message` at info.""" + + self._record(message=message, level=LogLevel.INFO) + + def warning(self, message: str) -> None: + """Log `message` at warning.""" + + self._record(message=message, level=LogLevel.WARNING) + + def error(self, message: str) -> None: + """Log `message` at error.""" + + self._record(message=message, level=LogLevel.ERROR) + + def _record(self, *, message: str, level: LogLevel) -> None: + self._recorder.log(message=str(message), level=level) + if self._logger is not None: + self._logger.log(_PYTHON_LEVELS[level], "%s", message) diff --git a/src/sqlbuild/adapter/contract/classes/statement_recorder.py b/src/sqlbuild/adapter/contract/classes/statement_recorder.py index e3fb9e59a8..79f6b5d3f8 100644 --- a/src/sqlbuild/adapter/contract/classes/statement_recorder.py +++ b/src/sqlbuild/adapter/contract/classes/statement_recorder.py @@ -5,7 +5,7 @@ from collections.abc import Iterable from sqlbuild.adapter.contract.models import LifeCycleEvent -from sqlbuild.adapter.contract.types import LifeCycleEventKind +from sqlbuild.adapter.contract.types import LifeCycleEventKind, LogLevel class StatementRecorder: @@ -22,8 +22,10 @@ def record_many(self, statements: Iterable[str]) -> None: for statement in statements: self.events.append(LifeCycleEvent(kind=LifeCycleEventKind.SQL, content=statement)) - def log(self, message: str) -> None: - self.events.append(LifeCycleEvent(kind=LifeCycleEventKind.LOG, content=message)) + def log(self, *, message: str, level: LogLevel | None = None) -> None: + self.events.append( + LifeCycleEvent(kind=LifeCycleEventKind.LOG, content=message, level=level) + ) def snapshot(self) -> tuple[LifeCycleEvent, ...]: return tuple(self.events) diff --git a/src/sqlbuild/adapter/contract/classes/strict_adapter.py b/src/sqlbuild/adapter/contract/classes/strict_adapter.py index 63cf7b067d..1222e2b74c 100644 --- a/src/sqlbuild/adapter/contract/classes/strict_adapter.py +++ b/src/sqlbuild/adapter/contract/classes/strict_adapter.py @@ -161,6 +161,14 @@ def create_table_as_replaces(self) -> bool: return False + def rebuilt_table_row_count( + self, *, connection: Any, database: str | None, schema: str | None, name: str + ) -> int | None: + """Optional: the rows of a table just rebuilt in full, from metadata; None unless exact.""" + + del connection, database, schema, name + return None + def render_cursor_operand(self, *, expression: str, cursor_type: str | None) -> str: """Optional: the cursor-column expression compared with cursor bounds and aggregated.""" diff --git a/src/sqlbuild/adapter/contract/models.py b/src/sqlbuild/adapter/contract/models.py index 789bc8bf2d..f6faeb0ee9 100644 --- a/src/sqlbuild/adapter/contract/models.py +++ b/src/sqlbuild/adapter/contract/models.py @@ -15,6 +15,7 @@ HistoricalSnapshotCloseStyle, HistoricalSnapshotInsertStyle, LifeCycleEventKind, + LogLevel, MigrationTransfer, RelationReadStatus, RetentionChangePhase, @@ -464,3 +465,4 @@ class LifeCycleEvent: kind: LifeCycleEventKind content: str + level: LogLevel | None = None diff --git a/src/sqlbuild/adapter/contract/types.py b/src/sqlbuild/adapter/contract/types.py index 80d52e02f0..fff7e430ae 100644 --- a/src/sqlbuild/adapter/contract/types.py +++ b/src/sqlbuild/adapter/contract/types.py @@ -101,6 +101,14 @@ class LifeCycleEventKind(StrEnum): LOG = "log" +class LogLevel(StrEnum): + """The level of a line a node logs with `ctx.log`.""" + + INFO = "info" + WARNING = "warning" + ERROR = "error" + + class FrameworkType(StrEnum): STRING = "string" INTEGER = "integer" diff --git a/src/sqlbuild/adapters/bigquery/classes/bigquery_adapter.py b/src/sqlbuild/adapters/bigquery/classes/bigquery_adapter.py index 90fc9df457..debd93551d 100644 --- a/src/sqlbuild/adapters/bigquery/classes/bigquery_adapter.py +++ b/src/sqlbuild/adapters/bigquery/classes/bigquery_adapter.py @@ -2620,6 +2620,15 @@ def normalize_row_diff_numeric_type(self, column_type: str) -> str | None: def format_row_diff_decimal_sql(self, value: Decimal) -> str: return format(value, "f") + def rebuilt_table_row_count( + self, *, connection: Any, database: str | None, schema: str | None, name: str + ) -> int | None: + """A table's ``num_rows`` is exact once a query job wrote it, with no streaming buffer.""" + + return self.estimate_relation_row_count( + connection=connection, database=database, schema=schema, name=name, metadata_only=True + ).row_count + def estimate_relation_row_count( self, *, diff --git a/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py b/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py index 321580ceff..863016705c 100644 --- a/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py +++ b/src/sqlbuild/adapters/clickhouse/classes/clickhouse_adapter.py @@ -119,6 +119,7 @@ from sqlbuild.adapters.clickhouse.constants import ( DEFAULT_COLUMN_DEFAULT_KIND, DEFAULT_DATABASE, + EXACT_ROW_COUNT_ENGINES, EXCHANGE_UNSUPPORTED_CODES, EXPECTED_OUTPUT_COLUMNS_CONFIG_KEY, FRESH_GENERATION_CLAUSE, @@ -476,6 +477,22 @@ def physical_relation_generation( return None return generation_comment(tuple(row)).removeprefix(GENERATION_COMMENT_PREFIX) + def rebuilt_table_row_count( + self, *, connection: Any, database: str | None, schema: str | None, name: str + ) -> int | None: + """``total_rows`` of plain MergeTree tables; merging engines count rows before merges.""" + + del database + row: Any = self.execute( + connection=connection, + sql="SELECT engine, total_rows FROM system.tables WHERE " + + _database_filter(schema) + + f" AND name = {quote_string(name)}", + ).fetchone() + if row is None or row[1] is None or str(row[0]) not in EXACT_ROW_COUNT_ENGINES: + return None + return int(row[1]) + def estimate_relation_row_count( self, *, diff --git a/src/sqlbuild/adapters/clickhouse/constants.py b/src/sqlbuild/adapters/clickhouse/constants.py index 783c6dfa4d..12b05306d1 100644 --- a/src/sqlbuild/adapters/clickhouse/constants.py +++ b/src/sqlbuild/adapters/clickhouse/constants.py @@ -131,3 +131,7 @@ "GROUP BY cluster, shard_num)" ) OTHER_REPLICAS_NOTICE: str = "usage read from this server only; other replicas not checked" + +EXACT_ROW_COUNT_ENGINES: frozenset[str] = frozenset( + {"MergeTree", "ReplicatedMergeTree", "SharedMergeTree"} +) diff --git a/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py b/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py index 4979391f57..041c1bf535 100644 --- a/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py +++ b/src/sqlbuild/adapters/snowflake/classes/snowflake_adapter.py @@ -1423,6 +1423,15 @@ def drop_table( statement_recorder.record(statement) self.execute(connection=connection, sql=statement) + def rebuilt_table_row_count( + self, *, connection: Any, database: str | None, schema: str | None, name: str + ) -> int | None: + """Snowflake's metadata row count of a standard table is exact.""" + + return self.estimate_relation_row_count( + connection=connection, database=database, schema=schema, name=name, metadata_only=True + ).row_count + def create_table_as_replaces(self) -> bool: return True diff --git a/src/sqlbuild/assets.py b/src/sqlbuild/assets.py index c242b54be1..e744f9958d 100644 --- a/src/sqlbuild/assets.py +++ b/src/sqlbuild/assets.py @@ -21,7 +21,7 @@ __all__ = ("AssetContext", "SkipMode", "asset", "get_asset_definition") -def asset( +def asset( # noqa: PLR0913 function: Callable[..., object] | None = None, *, name: str | None = None, @@ -37,8 +37,9 @@ def asset( columns: Sequence[PythonNodeColumnSpec | SourceColumnEntry] = (), column_lineage: Mapping[str, Sequence[ColumnLineageRefSpec | ColumnLineageRef]] | None = None, retry: RetryPolicy | None = None, + for_each: Callable[..., object] | None = None, ) -> Callable[..., object] | Callable[[Callable[..., object]], Callable[..., object]]: - """Mark a Python function as a SQLBuild asset.""" + """Mark a Python function as a SQLBuild asset; `for_each` makes one node per discovered item.""" return apply_asset( function=function, @@ -51,6 +52,7 @@ def asset( columns=columns, column_lineage=column_lineage, retry=retry, + for_each=for_each, ) diff --git a/src/sqlbuild/assets.pyi b/src/sqlbuild/assets.pyi index ae882c433e..e9c85d8758 100644 --- a/src/sqlbuild/assets.pyi +++ b/src/sqlbuild/assets.pyi @@ -31,5 +31,6 @@ def asset( columns: Sequence[PythonNodeColumnSpec | SourceColumnEntry] = (), column_lineage: Mapping[str, Sequence[ColumnLineageRefSpec | ColumnLineageRef]] | None = None, retry: RetryPolicy | None = None, + for_each: Callable[..., object] | None = None, ) -> Callable[[Callable[..., object]], Callable[..., object]]: ... def get_asset_definition(function: Callable[..., object]) -> AssetDefinition | None: ... diff --git a/src/sqlbuild/cli/entry/constants.py b/src/sqlbuild/cli/entry/constants.py index 3bff31b705..519bc2a1e1 100644 --- a/src/sqlbuild/cli/entry/constants.py +++ b/src/sqlbuild/cli/entry/constants.py @@ -4,3 +4,5 @@ NATIVE_ALLOCATOR_PURGE_DELAY_MILLISECONDS: str = "10" OUTPUT_STREAM_ENCODING: str = "utf-8" OUTPUT_STREAM_ERRORS: str = "backslashreplace" +INTERRUPTED_EXIT_CODE: int = 130 +INTERRUPTED_LINE: str = "error: interrupted (Ctrl+C)" diff --git a/src/sqlbuild/cli/entry/main/launched.py b/src/sqlbuild/cli/entry/main/launched.py index 4925ae9ab4..05f8b48e17 100644 --- a/src/sqlbuild/cli/entry/main/launched.py +++ b/src/sqlbuild/cli/entry/main/launched.py @@ -4,6 +4,8 @@ import sys from sqlbuild.cli.entry.constants import ( + INTERRUPTED_EXIT_CODE, + INTERRUPTED_LINE, NATIVE_ALLOCATOR_PURGE_DELAY_MILLISECONDS, NATIVE_ALLOCATOR_PURGE_DELAY_VARIABLE, ) @@ -16,10 +18,35 @@ def main() -> int: os.environ.setdefault( NATIVE_ALLOCATOR_PURGE_DELAY_VARIABLE, NATIVE_ALLOCATOR_PURGE_DELAY_MILLISECONDS ) - from sqlbuild._native import LAUNCH_RECORD_OPTION, defer_compile_teardown_to_exit + try: + from sqlbuild._native import ( + LAUNCH_RECORD_OPTION, + defer_compile_teardown_to_exit, + run_interruptible, + ) + from sqlbuild.executor.python_nodes.main.exit_past_abandoned_steps import ( + exit_past_abandoned_steps, + ) + except KeyboardInterrupt: + _ = sys.stderr.write(f"{INTERRUPTED_LINE}\n") + return INTERRUPTED_EXIT_CODE _ = defer_compile_teardown_to_exit() arguments: list[str] = sys.argv[1:] offered: bool = bool(arguments) and arguments[0].startswith(LAUNCH_RECORD_OPTION) sys.argv = [sys.argv[0], *arguments[int(offered) :]] - return run_cli(arguments) + + def run_command() -> int: + """Run the command, then end past a cancelled step still running, inside the watch.""" + + try: + exit_code: int = run_cli(arguments) + except KeyboardInterrupt: + _ = exit_past_abandoned_steps( + exit_code=INTERRUPTED_EXIT_CODE, last_line=INTERRUPTED_LINE + ) + raise + _ = exit_past_abandoned_steps(exit_code=exit_code) + return exit_code + + return run_interruptible(run_command) diff --git a/src/sqlbuild/compiler/discovery/_helpers/validation/discovery.py b/src/sqlbuild/compiler/discovery/_helpers/validation/discovery.py index 940479ec1e..42775c52a7 100644 --- a/src/sqlbuild/compiler/discovery/_helpers/validation/discovery.py +++ b/src/sqlbuild/compiler/discovery/_helpers/validation/discovery.py @@ -15,7 +15,7 @@ from sqlbuild.python_nodes.main.read_asset_definition import read_asset_definition from sqlbuild.python_nodes.main.read_check_definition import read_check_definition from sqlbuild.python_nodes.main.read_loader_definition import read_loader_definition -from sqlbuild.python_nodes.models import NodeSetRef, SqlResourceRef +from sqlbuild.python_nodes.models import DiscoveredItemRef, NodeSetRef, SqlResourceRef type _PythonNode = DiscoveredLoaderFunction | DiscoveredAssetFunction | DiscoveredCheckFunction @@ -79,6 +79,8 @@ def _loader_has_decorator_config(loader_function: DiscoveredLoaderFunction) -> b def _decorated_name(dependency: object) -> str | None: + if isinstance(dependency, DiscoveredItemRef): + return dependency.name if not callable(dependency): return None for read_definition in _DEFINITION_READERS: diff --git a/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py b/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py index afa2591dde..42f6aed335 100644 --- a/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py +++ b/src/sqlbuild/compiler/python_nodes/_helpers/user_inventory.py @@ -14,6 +14,7 @@ from sqlbuild.python_nodes.models import ( AssetDefinition, CheckDefinition, + DiscoveredItemRef, LoaderDefinition, ) @@ -44,7 +45,10 @@ def python_node_identity( def python_node_dependency_key(dependency: object) -> object | tuple[str, str]: - """The node name a decorated dependency declares, or the dependency itself.""" + """The node name a decorated dependency or discovered item names, or the dependency itself.""" + + if isinstance(dependency, DiscoveredItemRef): + return ("name", dependency.name) loader_definition: LoaderDefinition | None = ( read_loader_definition(dependency) if callable(dependency) else None diff --git a/src/sqlbuild/discovery.py b/src/sqlbuild/discovery.py new file mode 100644 index 0000000000..9d8b7444b1 --- /dev/null +++ b/src/sqlbuild/discovery.py @@ -0,0 +1,28 @@ +"""Public API for discovered nodes: one asset node per item a discover function returns.""" + +from __future__ import annotations + +from collections.abc import Callable + +from sqlbuild.python_nodes.main.apply_discover import apply_discover +from sqlbuild.python_nodes.main.read_discover_definition import read_discover_definition +from sqlbuild.python_nodes.models import DiscoverDefinition, Discovered, Item + +__all__ = ("Discovered", "Item", "discover", "get_discover_definition") + + +def discover( + function: Callable[..., object] | None = None, + *, + name: str | None = None, + check_every: str | None = None, +) -> Callable[..., object] | Callable[[Callable[..., object]], Callable[..., object]]: + """Mark a function that returns `Discovered`; only a location calls it, when it publishes.""" + + return apply_discover(function=function, name=name, check_every=check_every) + + +def get_discover_definition(function: Callable[..., object]) -> DiscoverDefinition | None: + """Return SQLBuild discover metadata from a decorated function, if present.""" + + return read_discover_definition(function) diff --git a/src/sqlbuild/discovery.pyi b/src/sqlbuild/discovery.pyi new file mode 100644 index 0000000000..82a99a39c9 --- /dev/null +++ b/src/sqlbuild/discovery.pyi @@ -0,0 +1,16 @@ +from collections.abc import Callable +from typing import overload + +from sqlbuild.python_nodes.models import DiscoverDefinition +from sqlbuild.python_nodes.models import Discovered as Discovered +from sqlbuild.python_nodes.models import Item as Item + +__all__ = ("Discovered", "Item", "discover", "get_discover_definition") + +@overload +def discover(function: Callable[..., object]) -> Callable[..., object]: ... +@overload +def discover( + *, name: str | None = None, check_every: str | None = None +) -> Callable[[Callable[..., object]], Callable[..., object]]: ... +def get_discover_definition(function: Callable[..., object]) -> DiscoverDefinition | None: ... diff --git a/src/sqlbuild/executor/build/_helpers/source_node.py b/src/sqlbuild/executor/build/_helpers/source_node.py index 46ce2b0ae4..d5ce6949e4 100644 --- a/src/sqlbuild/executor/build/_helpers/source_node.py +++ b/src/sqlbuild/executor/build/_helpers/source_node.py @@ -3,6 +3,7 @@ from __future__ import annotations import dataclasses +import functools import time from collections.abc import Callable from typing import Any @@ -88,6 +89,9 @@ def execute_build_source_node( result_store=result_store, schema_prepared=schema_prepared, project_relations=runtime.project_relations, + on_rows_written=_rows_written_for( + key=f"source:{source_entry.name}", callbacks=callbacks + ), ), statement_recorder=StatementRecorder(), loader_ref_entries=loader_ref_entries, @@ -108,3 +112,12 @@ def execute_build_source_node( result_store=result_store, ) return timed_result + + +def _rows_written_for(*, key: str, callbacks: BuildCallbacks) -> Callable[[int], None] | None: + """Report one loader's rows so far under its node key.""" + + on_rows_written: Callable[[str, int], None] | None = callbacks.on_rows_written + if on_rows_written is None: + return None + return functools.partial(on_rows_written, key) diff --git a/src/sqlbuild/executor/build/classes/build_scheduler.py b/src/sqlbuild/executor/build/classes/build_scheduler.py index a52bb4b1aa..e3ec5443af 100644 --- a/src/sqlbuild/executor/build/classes/build_scheduler.py +++ b/src/sqlbuild/executor/build/classes/build_scheduler.py @@ -33,6 +33,7 @@ SqlTestPlanEntry, TableTypePlanEntry, audit_resource_id, + output_node_scope, sql_test_resource_id, ) from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter @@ -701,12 +702,17 @@ def _execute_concurrent_microbatch_node( self, *, key: CompiledObjectKey, pool: ThreadPoolExecutor, connection: Any ) -> ModelExecutionResult: try: - with CostContext.scope( - run_id=self._run_id, - resource_type=str(key.resource_type), - resource_name=key.name, - ledger_path=(self._runtime_dir / "executions" / self._run_id / "statements.jsonl"), - on_statement_complete=self._on_statement_complete, + with ( + output_node_scope(f"{key.resource_type}:{key.name}"), + CostContext.scope( + run_id=self._run_id, + resource_type=str(key.resource_type), + resource_name=key.name, + ledger_path=( + self._runtime_dir / "executions" / self._run_id / "statements.jsonl" + ), + on_statement_complete=self._on_statement_complete, + ), ): failure: str | None = self._switch_failure(key=key, connection=connection) if failure is not None: @@ -1006,12 +1012,17 @@ def _execute_node( plan_action=None if planned is None else str(planned.action), plan_reason_code=None if planned is None else str(planned.reason), ) as lifecycle: - with CostContext.scope( - run_id=self._run_id, - resource_type=str(key.resource_type), - resource_name=key.name, - ledger_path=(self._runtime_dir / "executions" / self._run_id / "statements.jsonl"), - on_statement_complete=self._on_statement_complete, + with ( + output_node_scope(f"{key.resource_type}:{key.name}"), + CostContext.scope( + run_id=self._run_id, + resource_type=str(key.resource_type), + resource_name=key.name, + ledger_path=( + self._runtime_dir / "executions" / self._run_id / "statements.jsonl" + ), + on_statement_complete=self._on_statement_complete, + ), ): result: ( ModelExecutionResult diff --git a/src/sqlbuild/executor/build/models.py b/src/sqlbuild/executor/build/models.py index 0f3ede6d6a..562f493977 100644 --- a/src/sqlbuild/executor/build/models.py +++ b/src/sqlbuild/executor/build/models.py @@ -119,6 +119,7 @@ class BuildCallbacks: on_progress: Callable[[str], None] | None = None on_sub_progress: Callable[[str], None] | None = None on_batch_complete: Callable[[MicrobatchBatchProgress], None] | None = None + on_rows_written: Callable[[str, int], None] | None = None on_node_start: NodeStartCallback | None = None on_node_complete: Callable[[object], None] | None = None before_node_write: BeforeNodeWriteCallback | None = None diff --git a/src/sqlbuild/executor/custom/models.py b/src/sqlbuild/executor/custom/models.py index 993b5caf43..07640a3748 100644 --- a/src/sqlbuild/executor/custom/models.py +++ b/src/sqlbuild/executor/custom/models.py @@ -9,6 +9,7 @@ from sqlbuild._native import SchemaFinding from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.adapter.contract.classes.node_logger import NodeLogger from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder from sqlbuild.adapter.contract.models import ColumnInfo, RelationInfo from sqlbuild.executor.auditing.models import AuditExecutionResult @@ -55,9 +56,11 @@ def execute_sql(self, sql: str) -> Any: statement_recorder=self.statement_recorder, ) - def log(self, message: str) -> None: - """Record a log message for verbose output.""" - self.statement_recorder.log(message) + @property + def log(self) -> NodeLogger: + """`ctx.log.info(...)`, `.warning(...)` or `.error(...)`, kept with the run's events.""" + + return NodeLogger(recorder=self.statement_recorder, logger=self.logger) def qualify_name( self, diff --git a/src/sqlbuild/executor/load/_helpers/staging.py b/src/sqlbuild/executor/load/_helpers/staging.py index 0291b18d29..c451ffc98a 100644 --- a/src/sqlbuild/executor/load/_helpers/staging.py +++ b/src/sqlbuild/executor/load/_helpers/staging.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Callable from typing import Any from sqlbuild._native import ContractPolicy, SourceEntry, fit_auxiliary_relation_name @@ -29,8 +30,9 @@ def write_loader_rows_to_staging( connection: Any, staging: str, statement_recorder: StatementRecorder, + on_rows_written: Callable[[int], None] | None = None, ) -> int: - """Write framework-managed loader rows into one staging table.""" + """Write framework-managed loader rows into one staging table, reporting the rows so far.""" default_load_batch_size: int = 10000 batch_size: int = source_entry.load_batch_size or default_load_batch_size @@ -99,6 +101,8 @@ def write_loader_rows_to_staging( ) staging_created = True rows_loaded += len(batch) + if on_rows_written is not None: + on_rows_written(rows_loaded) if not staging_created: sql = build_rows_sql( adapter=adapter, diff --git a/src/sqlbuild/executor/load/main/_execute.py b/src/sqlbuild/executor/load/main/_execute.py index d2b6c0c3a8..d9e78b9b34 100644 --- a/src/sqlbuild/executor/load/main/_execute.py +++ b/src/sqlbuild/executor/load/main/_execute.py @@ -169,6 +169,7 @@ def _execute_source_load( connection=connection, staging=staging, statement_recorder=statement_recorder, + on_rows_written=runtime.on_rows_written, ) adapter = _apply_source_write_strategy( adapter=adapter, @@ -219,6 +220,7 @@ def _execute_source_load( resource_kind=resource_kind, staging_relation=staging, rows_loaded=rows_loaded, + rows_affected=rows_loaded, duration_ms=int((time.monotonic() - start) * 1000), lifecycle_events=statement_recorder.snapshot(), ) diff --git a/src/sqlbuild/executor/load/models.py b/src/sqlbuild/executor/load/models.py index 7a0bed956b..58e26bb7a1 100644 --- a/src/sqlbuild/executor/load/models.py +++ b/src/sqlbuild/executor/load/models.py @@ -11,6 +11,7 @@ from sqlbuild._native import DiscoveredLoaderFunction, SourceEntry, TargetSettings from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.adapter.contract.classes.node_logger import NodeLogger from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder from sqlbuild.adapter.contract.models import ColumnInfo, LifeCycleEvent from sqlbuild.adapter.contract.types import LoaderLogicalType @@ -163,8 +164,11 @@ def query(self, sql: str) -> Any: self.statement_recorder.record(sql) return self.adapter.execute(connection=self.connection, sql=sql) - def log(self, message: str) -> None: - self.statement_recorder.log(message) + @property + def log(self) -> NodeLogger: + """`ctx.log.info(...)`, `.warning(...)` or `.error(...)`, kept with the run's events.""" + + return NodeLogger(recorder=self.statement_recorder, logger=self.logger) def progress(self, message: str) -> None: if self.on_progress is not None: @@ -249,7 +253,7 @@ def _record_resolved(self, relation_ref: LoaderRelationRef) -> None: @dataclass(frozen=True) class LoadExecutionResult: - """Execution result for one source loader.""" + """Execution result for one source loader; `rows_affected` is None unless it wrote rows.""" source_name: str loader_name: str @@ -258,6 +262,7 @@ class LoadExecutionResult: resource_kind: ExecutionResourceKind = ExecutionResourceKind.SOURCE staging_relation: str | None = None rows_loaded: int = 0 + rows_affected: int | None = None duration_ms: int | None = None lifecycle_events: tuple[LifeCycleEvent, ...] = field(default_factory=tuple) skip_mode: SkipMode | None = None @@ -302,6 +307,7 @@ class LoadRuntimeParams: result_store: Any | None = None schema_prepared: bool = False project_relations: Mapping[SqlResourceRef, str] | None = None + on_rows_written: Callable[[int], None] | None = None @dataclass(frozen=True) diff --git a/src/sqlbuild/executor/node_results/classes/dependency_result_reader.py b/src/sqlbuild/executor/node_results/classes/dependency_result_reader.py index a68ff14d86..e7416be2be 100644 --- a/src/sqlbuild/executor/node_results/classes/dependency_result_reader.py +++ b/src/sqlbuild/executor/node_results/classes/dependency_result_reader.py @@ -5,10 +5,12 @@ from collections.abc import Callable from typing import Any +from sqlbuild.compiler.python_nodes.types import PythonNodeKind from sqlbuild.errors.contracts.exceptions import ExecutorInputError from sqlbuild.executor.node_results.constants import RESULT_DEPENDENCY_ATTRIBUTES from sqlbuild.executor.node_results.models import NodeResultEnvelope from sqlbuild.executor.python_nodes.constants import MISSING_DEFAULT +from sqlbuild.python_nodes.models import DiscoveredItemRef class DependencyResultReader: @@ -56,8 +58,10 @@ def result_dependency_identity(self, node_function: Callable[..., object]) -> tu return identity def result_node_identity(self, node_function: Callable[..., object]) -> tuple[str, str] | None: - """Return the `(kind, name)` of a decorated asset or loader, else None.""" + """Return the `(kind, name)` of a decorated asset or loader, or a discovered item's node.""" + if isinstance(node_function, DiscoveredItemRef): + return PythonNodeKind.ASSET.value, node_function.name for attribute, kind in RESULT_DEPENDENCY_ATTRIBUTES: definition: object = getattr(node_function, attribute, None) if definition is None: diff --git a/src/sqlbuild/executor/node_results/classes/direct_store.py b/src/sqlbuild/executor/node_results/classes/direct_store.py index 54f5d0723f..4f4b922822 100644 --- a/src/sqlbuild/executor/node_results/classes/direct_store.py +++ b/src/sqlbuild/executor/node_results/classes/direct_store.py @@ -2,6 +2,7 @@ from __future__ import annotations +from contextlib import AbstractContextManager, nullcontext from dataclasses import replace from typing import Any @@ -28,32 +29,37 @@ def __init__( database: str | None, schema: str | None, previous_locations: tuple[tuple[str | None, str | None], ...] = (), + write_lock: AbstractContextManager[Any] | None = None, ) -> None: self.adapter: BaseAdapter = adapter self.connection: Any = connection self.previous_locations: tuple[tuple[str | None, str | None], ...] = previous_locations + self._write_lock: AbstractContextManager[Any] = ( + nullcontext() if write_lock is None else write_lock + ) super().__init__(database=database, schema=schema) def write(self, record: NodeResultRecord) -> None: if self.schema is None: return - self.adapter.ensure_schema( - connection=self.connection, - database=self.database, - schema=self.schema, - statement_recorder=StatementRecorder(), - ) - write_node_result_record( - connection=self.connection, - execute=self.adapter.execute, - database=self.database, - schema=self.schema, - record=record, - render_qualified_name=self.adapter.render_qualified_name, - render_framework_type=self.adapter.render_framework_type, - render_create_table_sql=self.adapter.render_create_node_result_table_sql, - render_create_index_sqls=self.adapter.render_create_node_result_index_sqls, - ) + with self._write_lock: + self.adapter.ensure_schema( + connection=self.connection, + database=self.database, + schema=self.schema, + statement_recorder=StatementRecorder(), + ) + write_node_result_record( + connection=self.connection, + execute=self.adapter.execute, + database=self.database, + schema=self.schema, + record=record, + render_qualified_name=self.adapter.render_qualified_name, + render_framework_type=self.adapter.render_framework_type, + render_create_table_sql=self.adapter.render_create_node_result_table_sql, + render_create_index_sqls=self.adapter.render_create_node_result_index_sqls, + ) self._cache_record(record=record) def _read_persisted(self, *, query: NodeResultQuery) -> tuple[NodeResultEnvelope, ...]: diff --git a/src/sqlbuild/executor/node_results/main/_direct_store.py b/src/sqlbuild/executor/node_results/main/_direct_store.py index 5b989c81d9..57e1cce88d 100644 --- a/src/sqlbuild/executor/node_results/main/_direct_store.py +++ b/src/sqlbuild/executor/node_results/main/_direct_store.py @@ -2,6 +2,7 @@ from __future__ import annotations +from contextlib import AbstractContextManager from typing import Any from sqlbuild._native import TargetSettings @@ -17,6 +18,7 @@ def build_direct_node_result_store( database: str | None, schema: str | None, target_config: TargetSettings | None = None, + write_lock: AbstractContextManager[Any] | None = None, ) -> DirectNodeResultStore: """Build a direct-mode node result store that, for one release, also reads older locations.""" @@ -30,6 +32,7 @@ def build_direct_node_result_store( connection=connection, database=database, schema=schema, + write_lock=write_lock, previous_locations=tuple( location for location in earlier if location != (database, schema) ), diff --git a/src/sqlbuild/executor/python_nodes/_helpers/discovered_items.py b/src/sqlbuild/executor/python_nodes/_helpers/discovered_items.py new file mode 100644 index 0000000000..6f73672fe4 --- /dev/null +++ b/src/sqlbuild/executor/python_nodes/_helpers/discovered_items.py @@ -0,0 +1,71 @@ +"""The discovered item an asset node runs for: its arguments, context and placeholder failure.""" + +from __future__ import annotations + +from collections.abc import Mapping + +from sqlbuild.executor.python_nodes.constants import ( + CONNECTION_PRIVATE_MEMORY_DATABASE_KEYS, + MEMORY_DATABASE, + MIN_PARALLEL_ITEMS, +) +from sqlbuild.executor.python_nodes.models import DiscoveredContext, PythonNodeRuntime +from sqlbuild.executor.python_nodes.types import ExecutablePythonNode + + +def item_args(node: ExecutablePythonNode) -> dict[str, object] | None: + """The arguments a discovered item's node is called with; `None` for any other node.""" + + discovered: Mapping[str, object] | None = node.discovered + if discovered is None: + return None + return _string_keyed(discovered.get("args")) + + +def discovered_context(node: ExecutablePythonNode) -> DiscoveredContext | None: + """The item and set tags `ctx.discovered` gives a discovered item's node.""" + + discovered: Mapping[str, object] | None = node.discovered + if discovered is None or discovered.get("placeholder"): + return None + return DiscoveredContext( + set=str(discovered["set"]), + item=str(discovered["item"]), + tags=_string_keyed(discovered.get("tags")), + ) + + +def placeholder_failure(node: ExecutablePythonNode) -> str | None: + """Why the placeholder of a set that never succeeded cannot run; `None` for any other node.""" + + discovered: Mapping[str, object] | None = node.discovered + if discovered is None or not discovered.get("placeholder"): + return None + error: object = discovered.get("error") + return f"never discovered: {error if error else 'no discovery has run'}" + + +def _string_keyed(value: object) -> dict[str, object]: + """A saved JSON object as a dict; anything else as an empty one.""" + + if not isinstance(value, Mapping): + return {} + return {str(key): item for key, item in value.items()} + + +def parallel_set( + *, discovered: Mapping[str, object] | None, runtime: PythonNodeRuntime +) -> tuple[str, int] | None: + """The set and `max_parallel` of an item that may run beside others; `None` runs serially.""" + + if discovered is None or discovered.get("placeholder"): + return None + limit: object = discovered.get("max_parallel") + if not isinstance(limit, int) or limit < MIN_PARALLEL_ITEMS: + return None + key: str | None = CONNECTION_PRIVATE_MEMORY_DATABASE_KEYS.get(runtime.adapter.adapter_name) + if key is not None: + database: str = str(runtime.connection_config.get(key, MEMORY_DATABASE)) + if database == MEMORY_DATABASE: + return None + return str(discovered["set"]), limit diff --git a/src/sqlbuild/executor/python_nodes/_helpers/execution.py b/src/sqlbuild/executor/python_nodes/_helpers/execution.py index 52f77589d2..b07a9a1914 100644 --- a/src/sqlbuild/executor/python_nodes/_helpers/execution.py +++ b/src/sqlbuild/executor/python_nodes/_helpers/execution.py @@ -8,8 +8,9 @@ from dataclasses import replace from typing import Any -from sqlbuild._native import CostContext +from sqlbuild._native import CostContext, output_node_scope from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder +from sqlbuild.adapter.contract.models import LifeCycleEvent from sqlbuild.compiler.python_nodes.types import ( PythonNodeFanInAction, PythonNodeKind, @@ -19,6 +20,11 @@ from sqlbuild.executor.node_results.main._direct_store import build_direct_node_result_store from sqlbuild.executor.node_results.models import NodeResultRecord from sqlbuild.executor.node_results.types import NodeResultStatus +from sqlbuild.executor.python_nodes._helpers.discovered_items import ( + discovered_context, + item_args, + placeholder_failure, +) from sqlbuild.executor.python_nodes._helpers.node_warehouse import node_runtime from sqlbuild.executor.python_nodes._helpers.relation_guard import build_python_node_relation_guard from sqlbuild.executor.python_nodes._helpers.results import ( @@ -45,6 +51,7 @@ RetryPolicy, SqlResourceRef, ) +from sqlbuild.runtime.execution_limits.main.bookkeeping_statements import bookkeeping_statements from sqlbuild.runtime.observability.classes.operation_lifecycle import ( OperationLifecycle, publish_retry_scheduled, @@ -108,10 +115,13 @@ def _execute_ready_node( on_result: OwnedResultCallback | None, ) -> PythonNodeExecutionResult: node_kind: PythonNodeKind = PythonNodeKind.ASSET - with CostContext.resource_scope( - resource_type=node_kind.value, - resource_name=node.name, - phase="execute", + with ( + output_node_scope(f"{node_kind.value}:{node.name}"), + CostContext.resource_scope( + resource_type=node_kind.value, + resource_name=node.name, + phase="execute", + ), ): with ResourceAttemptLifecycle( resource_id=f"{node_kind.value}:{node.name}", @@ -119,7 +129,7 @@ def _execute_ready_node( resource_name=node.name, run_id=runtime.run_id, ) as lifecycle: - result, skip_code = _execute_ready_node_in_cost_scope( + outcome, skip_code = _execute_ready_node_in_cost_scope( node=node, node_kind=node_kind, upstream_results=upstream_results, @@ -131,6 +141,9 @@ def _execute_ready_node( sleep=sleep, monotonic=monotonic, ) + result: PythonNodeExecutionResult = replace( + outcome, lifecycle_events=_logged_events(statement_recorder) + ) if on_result is not None: on_result(node=node, result=result) if result.status == PythonNodeStatus.SKIPPED: @@ -143,6 +156,12 @@ def _execute_ready_node( return result +def _logged_events(recorder: StatementRecorder) -> tuple[LifeCycleEvent, ...]: + """The node's `ctx.log` lines, the only events its result carries.""" + + return tuple(event for event in recorder.snapshot() if event.level is not None) + + def _execute_ready_node_in_cost_scope( *, node: ExecutablePythonNode, @@ -190,6 +209,16 @@ def _execute_ready_node_in_cost_scope( ) _persist_python_node_result(result_store=result_store, result=result, run_id=run_id) return result, None + never_discovered: str | None = placeholder_failure(node) + if never_discovered is not None: + result = PythonNodeExecutionResult( + node_name=node.name, + kind=node_kind, + status=PythonNodeStatus.FAILED, + error_message=never_discovered, + ) + _persist_python_node_result(result_store=result_store, result=result, run_id=run_id) + return result, None warnings: list[str] = [] context: AssetContext = _build_context( node=node, @@ -213,6 +242,8 @@ def _execute_ready_node_in_cost_scope( ) _persist_python_node_result(result_store=result_store, result=result, run_id=run_id) return result, None + if runtime.on_start is not None: + runtime.on_start(node.name) try: result: PythonNodeExecutionResult = _call_node_with_retry( node=node, @@ -241,40 +272,41 @@ def _persist_python_node_result( ) -> None: if result_store is None: return - record: NodeResultRecord = NodeResultRecord( - node_type=result.kind.value, - node_name=result.node_name, - target_database=result_store.database, - target_schema=result_store.schema, - target_name=None, - run_id=run_id, - status=result.status.value, - payload=result.payload, - metadata=result.metadata, - error_message=result.error_message or result.skip_reason, - materialized=result.materialized, - ) - try: - result_store.write(record) - except Exception as error: - if result.status != PythonNodeStatus.SUCCESS: - raise - result_store.write( - NodeResultRecord( - node_type=result.kind.value, - node_name=result.node_name, - target_database=result_store.database, - target_schema=result_store.schema, - target_name=None, - run_id=run_id, - status=NodeResultStatus.FAILED.value, - payload=None, - metadata={}, - error_message=str(error), - materialized=result.materialized, - ) + with bookkeeping_statements(): + record: NodeResultRecord = NodeResultRecord( + node_type=result.kind.value, + node_name=result.node_name, + target_database=result_store.database, + target_schema=result_store.schema, + target_name=None, + run_id=run_id, + status=result.status.value, + payload=result.payload, + metadata=result.metadata, + error_message=result.error_message or result.skip_reason, + materialized=result.materialized, ) - raise + try: + result_store.write(record) + except Exception as error: + if result.status != PythonNodeStatus.SUCCESS: + raise + result_store.write( + NodeResultRecord( + node_type=result.kind.value, + node_name=result.node_name, + target_database=result_store.database, + target_schema=result_store.schema, + target_name=None, + run_id=run_id, + status=NodeResultStatus.FAILED.value, + payload=None, + metadata={}, + error_message=str(error), + materialized=result.materialized, + ) + ) + raise def _call_node_with_retry( @@ -288,11 +320,14 @@ def _call_node_with_retry( ) -> PythonNodeExecutionResult: node_kind: PythonNodeKind = PythonNodeKind.ASSET if retry_policy is None: - with CostContext.resource_scope( - resource_type=node_kind.value, - resource_name=node.name, - phase="execute", - attempt=1, + with ( + output_node_scope(f"{node_kind.value}:{node.name}"), + CostContext.resource_scope( + resource_type=node_kind.value, + resource_name=node.name, + phase="execute", + attempt=1, + ), ): with OperationLifecycle( operation_kind="python_node", @@ -303,6 +338,7 @@ def _call_node_with_retry( function=node.function, context=context, providers=providers, + supplied_kwargs=item_args(node), ) result: PythonNodeExecutionResult = normalize_python_node_return( node_name=node.name, @@ -317,11 +353,14 @@ def _call_node_with_retry( while True: retry_error: BaseException | None = None delay_seconds: float | None = None - with CostContext.resource_scope( - resource_type=node_kind.value, - resource_name=node.name, - phase="execute", - attempt=attempt, + with ( + output_node_scope(f"{node_kind.value}:{node.name}"), + CostContext.resource_scope( + resource_type=node_kind.value, + resource_name=node.name, + phase="execute", + attempt=attempt, + ), ): with OperationLifecycle( operation_kind="python_node", @@ -333,6 +372,7 @@ def _call_node_with_retry( function=node.function, context=context, providers=providers, + supplied_kwargs=item_args(node), ) except retry_policy.retry_on as error: retry_error = error @@ -446,4 +486,6 @@ def _build_context( end_cursor_ts=runtime.end_cursor_ts, start_cursor_int=runtime.start_cursor_int, end_cursor_int=runtime.end_cursor_int, + discovered=discovered_context(node), + chain_run_id=runtime.chain_run_id, ) diff --git a/src/sqlbuild/executor/python_nodes/_helpers/fingerprinting.py b/src/sqlbuild/executor/python_nodes/_helpers/fingerprinting.py index 310f994670..2356f459f8 100644 --- a/src/sqlbuild/executor/python_nodes/_helpers/fingerprinting.py +++ b/src/sqlbuild/executor/python_nodes/_helpers/fingerprinting.py @@ -9,6 +9,7 @@ from sqlbuild._native import Fingerprint, PythonNodeIdentity, write_fingerprint from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.runtime.execution_limits.main.bookkeeping_statements import bookkeeping_statements def try_write_python_node_identity_fingerprint( @@ -34,32 +35,33 @@ def try_write_python_node_identity_fingerprint( ) return try: - _ = write_fingerprint( - connection=connection, - execute=adapter.execute, - database=database, - schema=schema, - fingerprint=Fingerprint( - node_type=identity.node_type, - node_name=identity.node_name, - target_database=database, - target_schema=schema, - target_name=target_name, - run_id=run_id, - definition_hash=identity.definition_hash, - version_hash=identity.version_hash, - schema_fingerprint=hashlib.sha256(b"").hexdigest(), - definition=identity.definition_json, - metadata_json=identity.metadata_json, - ts=datetime.now(tz=UTC), - ), - render_qualified_name=adapter.render_qualified_name, - render_framework_type=adapter.render_framework_type, - read_columns=adapter.get_columns, - render_add_columns=adapter.render_add_columns, - render_create_table_sql=adapter.render_create_fingerprint_table_sql, - render_create_index_sqls=adapter.render_create_fingerprint_index_sqls, - ) + with bookkeeping_statements(): + _ = write_fingerprint( + connection=connection, + execute=adapter.execute, + database=database, + schema=schema, + fingerprint=Fingerprint( + node_type=identity.node_type, + node_name=identity.node_name, + target_database=database, + target_schema=schema, + target_name=target_name, + run_id=run_id, + definition_hash=identity.definition_hash, + version_hash=identity.version_hash, + schema_fingerprint=hashlib.sha256(b"").hexdigest(), + definition=identity.definition_json, + metadata_json=identity.metadata_json, + ts=datetime.now(tz=UTC), + ), + render_qualified_name=adapter.render_qualified_name, + render_framework_type=adapter.render_framework_type, + read_columns=adapter.get_columns, + render_add_columns=adapter.render_add_columns, + render_create_table_sql=adapter.render_create_fingerprint_table_sql, + render_create_index_sqls=adapter.render_create_fingerprint_index_sqls, + ) except Exception as exc: resolved_logger.warning( "python identity fingerprint write failed for '%s': %s", diff --git a/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py b/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py index ad244d1b69..801e461e3f 100644 --- a/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py +++ b/src/sqlbuild/executor/python_nodes/_helpers/ingress_execution.py @@ -16,6 +16,7 @@ PythonNodeGraph, PythonSqlRunLifecyclePlan, SourceEntry, + output_node_scope, ) from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder from sqlbuild.compiler.python_nodes.types import PythonNodeKind, PythonNodeStatus, SkipMode @@ -26,14 +27,17 @@ from sqlbuild.executor.load.main._skipped_result import skipped_load_result from sqlbuild.executor.load.models import LoadExecutionResult, LoadRuntimeParams from sqlbuild.executor.node_results.main._direct_store import build_direct_node_result_store +from sqlbuild.executor.python_nodes._helpers.discovered_items import parallel_set from sqlbuild.executor.python_nodes._helpers.fingerprinting import ( try_write_python_node_identity_fingerprint, ) from sqlbuild.executor.python_nodes._helpers.lifecycle_nodes import build_ingress_lifecycle_nodes from sqlbuild.executor.python_nodes._helpers.node_warehouse import node_runtime +from sqlbuild.executor.python_nodes.classes.discovered_item_pool import DiscoveredItemPool from sqlbuild.executor.python_nodes.classes.ingress_results import IngressResultAccumulator from sqlbuild.executor.python_nodes.main._ready import run_ready_python_node from sqlbuild.executor.python_nodes.models import ( + DiscoveredItemCallbacks, IngressCallbacks, PythonIngressLoaderExecutorResult, PythonNodeExecutionResult, @@ -41,6 +45,8 @@ PythonNodeRuntime, ) from sqlbuild.executor.python_nodes.types import ExecutablePythonNode +from sqlbuild.executor.scheduling.classes.lifecycle_concurrency import LifecycleConcurrency +from sqlbuild.executor.scheduling.classes.lifecycle_progress import LifecycleProgress from sqlbuild.executor.scheduling.main._run_lifecycle import run_lifecycle_scheduler from sqlbuild.executor.scheduling.models import ( LifecycleExecutionNode, @@ -120,6 +126,14 @@ def execute_ingress_python_loader_nodes( run_state=run_state, results=results, ), + concurrency=_item_concurrency( + nodes=lifecycle_nodes, + python_graph=python_graph, + runtime=runtime, + callbacks=resolved_callbacks, + run_state=run_state, + results=results, + ), ) _record_scheduler_skips( scheduler_result=scheduler_result, @@ -136,6 +150,78 @@ def execute_ingress_python_loader_nodes( ) +def _item_concurrency( + *, + nodes: tuple[LifecycleExecutionNode, ...], + python_graph: PythonNodeGraph, + runtime: PythonNodeRuntime, + callbacks: IngressCallbacks, + run_state: PythonNodeRunState, + results: IngressResultAccumulator, +) -> LifecycleConcurrency | None: + """How ingress runs discovered items beside each other; `None` when none may.""" + + parallel: dict[str, tuple[str, int]] = {} + lifecycle_node: LifecycleExecutionNode + for lifecycle_node in nodes: + discovered_node: DiscoveredPythonNode = python_graph.nodes_by_name[lifecycle_node.name] + limited: tuple[str, int] | None = parallel_set( + discovered=None if discovered_node.asset is None else discovered_node.asset.discovered, + runtime=runtime, + ) + if limited is not None: + parallel[lifecycle_node.name] = limited + if not parallel: + return None + by_name: dict[str, LifecycleExecutionNode] = {node.name: node for node in nodes} + + def run(progress: LifecycleProgress) -> None: + def complete_item(*, node: ExecutablePythonNode, result: PythonNodeExecutionResult) -> None: + if callbacks.on_node_complete is not None: + callbacks.on_node_complete(result) + _finalize_ingress_python_result( + node=node, + result=result, + discovered_node=python_graph.nodes_by_name[node.name], + runtime=runtime, + callbacks=callbacks, + run_state=run_state, + results=results, + ) + progress.complete( + node=by_name[node.name], result=_python_result_to_lifecycle_result(result) + ) + + DiscoveredItemPool( + runtime=runtime, + run_state=run_state, + callbacks=DiscoveredItemCallbacks( + ready=lambda: tuple( + _to_executable_python_node(python_graph.nodes_by_name[node.name]) + for node in progress.startable(eligible=lambda node: node.name in parallel) + ), + upstream_results=lambda name: _python_upstream_results( + name=name, python_graph=python_graph, results=results + ), + complete=complete_item, + started=callbacks.on_asset_start, + cancelled=callbacks.on_node_cancelled, + ), + ).run(thread_limit=sum(dict(parallel.values()).values())) + + return LifecycleConcurrency(eligible=lambda node: node.name in parallel, run=run) + + +def _python_upstream_results( + *, name: str, python_graph: PythonNodeGraph, results: IngressResultAccumulator +) -> tuple[PythonNodeExecutionResult, ...]: + return tuple( + results.python_results_by_name[upstream_name] + for upstream_name in python_graph.upstream_deps.get(name, ()) + if upstream_name in results.python_results_by_name + ) + + def _execute_ingress_lifecycle_node( *, node: LifecycleExecutionNode, @@ -179,16 +265,14 @@ def _execute_ingress_python_node( results: IngressResultAccumulator, ) -> LifecycleNodeResult: executable_node: ExecutablePythonNode = _to_executable_python_node(node) - upstream_results: tuple[PythonNodeExecutionResult, ...] = tuple( - results.python_results_by_name[upstream_name] - for upstream_name in python_graph.upstream_deps.get(node.name, ()) - if upstream_name in results.python_results_by_name + upstream_results: tuple[PythonNodeExecutionResult, ...] = _python_upstream_results( + name=node.name, python_graph=python_graph, results=results ) result: PythonNodeExecutionResult = run_ready_python_node( node=executable_node, upstream_results=upstream_results, - runtime=runtime, + runtime=replace(runtime, on_start=callbacks.on_asset_start), statement_recorder=StatementRecorder(), run_state=run_state, on_result=partial( @@ -215,14 +299,17 @@ def _finalize_ingress_python_result( run_state: PythonNodeRunState, results: IngressResultAccumulator, ) -> None: - run_state.record_result(node_function=node.function, result=result) + run_state.record_result(result=result) results.record_python_result(name=discovered_node.name, result=result) if result.status != PythonNodeStatus.SUCCESS: return - with CostContext.resource_scope( - resource_type=discovered_node.kind.value, - resource_name=discovered_node.name, - phase="finalize", + with ( + output_node_scope(f"{discovered_node.kind.value}:{discovered_node.name}"), + CostContext.resource_scope( + resource_type=discovered_node.kind.value, + resource_name=discovered_node.name, + phase="finalize", + ), ): if callbacks.identity_recorder is not None: callbacks.identity_recorder(identity=discovered_node.identity, _target_name=None) @@ -270,10 +357,13 @@ def _execute_ingress_loader( with lifecycle as attempt: if callbacks.on_node_start is not None: callbacks.on_node_start(name=source_entry.name, resource_kind=resource_kind) - with CostContext.resource_scope( - resource_type=PythonNodeKind.LOADER.value, - resource_name=loader.name, - phase="load", + with ( + output_node_scope(f"source:{loader.name}"), + CostContext.resource_scope( + resource_type=PythonNodeKind.LOADER.value, + resource_name=loader.name, + phase="load", + ), ): runtime, warehouse_failure = node_runtime(runtime=runtime, name=node.name) result: LoadExecutionResult = ( @@ -381,10 +471,13 @@ def _record_scheduler_skips( mode=skip_mode, ) results.record_load_result(name=result.name, result=skipped_result) - with CostContext.resource_scope( - resource_type=PythonNodeKind.LOADER.value, - resource_name=result.name, - phase="finalize", + with ( + output_node_scope(f"source:{result.name}"), + CostContext.resource_scope( + resource_type=PythonNodeKind.LOADER.value, + resource_name=result.name, + phase="finalize", + ), ): persist_loader_result( result_store=result_store, @@ -429,6 +522,7 @@ def _to_executable_python_node(node: DiscoveredPythonNode) -> ExecutablePythonNo columns=node.asset.columns if node.asset is not None else (), column_lineage=node.asset.column_lineage if node.asset is not None else None, retry=node.asset.retry if node.asset is not None else None, + discovered=node.asset.discovered if node.asset is not None else None, ) diff --git a/src/sqlbuild/executor/python_nodes/_helpers/python_checks.py b/src/sqlbuild/executor/python_nodes/_helpers/python_checks.py index 472ed512aa..effb2aedf8 100644 --- a/src/sqlbuild/executor/python_nodes/_helpers/python_checks.py +++ b/src/sqlbuild/executor/python_nodes/_helpers/python_checks.py @@ -12,6 +12,7 @@ DiscoveredPythonNode, PythonNodeGraph, PythonNodeIdentity, + output_node_scope, ) from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder @@ -150,6 +151,7 @@ def _execute_one_python_check( adapter: BaseAdapter = runtime.adapter providers: ProviderContainer | None = runtime.providers with ( + output_node_scope(f"check:{check_function.name}"), CostContext.resource_scope( resource_type=PythonNodeKind.CHECK.value, resource_name=check_function.name, diff --git a/src/sqlbuild/executor/python_nodes/_helpers/results.py b/src/sqlbuild/executor/python_nodes/_helpers/results.py index 287ab6b0eb..113fb50d81 100644 --- a/src/sqlbuild/executor/python_nodes/_helpers/results.py +++ b/src/sqlbuild/executor/python_nodes/_helpers/results.py @@ -2,6 +2,9 @@ from __future__ import annotations +import traceback + +from sqlbuild._native import redact_diagnostic_text from sqlbuild.compiler.python_nodes.types import ( PythonNodeFanInAction, PythonNodeKind, @@ -9,6 +12,13 @@ SkipMode, ) from sqlbuild.errors.contracts.exceptions import ExecutorInputError +from sqlbuild.executor.python_nodes.constants import ( + ERROR_DETAIL_CHARS, + ERROR_SUMMARY_CHARS, + ERROR_SUMMARY_CUT, + TRACEBACK_ELIDED, + TRACEBACK_HEADER, +) from sqlbuild.executor.python_nodes.models import ( PythonCheckResult, PythonNodeExecutionResult, @@ -83,9 +93,35 @@ def build_python_node_failure_result( kind=kind, status=PythonNodeStatus.FAILED, error_message=str(error), + error_detail=traceback_tail(error=error), ) +def traceback_tail(*, error: BaseException) -> str: + """Return the error's redacted traceback, cut to its exception and last frames if too long.""" + + text: str = redact_diagnostic_text("".join(traceback.format_exception(error))) + if len(text) <= ERROR_DETAIL_CHARS: + return text + raised: str = redact_diagnostic_text("".join(traceback.format_exception_only(error))) + frames: list[str] = text.removesuffix(raised).splitlines(keepends=True) + if len(raised) > ERROR_SUMMARY_CHARS: + raised = raised[: ERROR_SUMMARY_CHARS - len(ERROR_SUMMARY_CUT)] + ERROR_SUMMARY_CUT + elided: str = TRACEBACK_ELIDED.format(count=len(frames)) + room: int = ERROR_DETAIL_CHARS - len(TRACEBACK_HEADER) - len(elided) - len(raised) + kept: list[str] = [] + for line in reversed(frames): + if len(line) > room: + break + kept.append(line) + room -= len(line) + kept.reverse() + if len(kept) == len(frames): + return "".join(kept) + raised + elided = TRACEBACK_ELIDED.format(count=len(frames) - len(kept)) + return TRACEBACK_HEADER + elided + "".join(kept) + raised + + def evaluate_python_node_fan_in( *, upstream_results: tuple[PythonNodeExecutionResult, ...] ) -> PythonNodeFanInDecision: diff --git a/src/sqlbuild/executor/python_nodes/classes/discovered_item_pool.py b/src/sqlbuild/executor/python_nodes/classes/discovered_item_pool.py new file mode 100644 index 0000000000..1343a2df19 --- /dev/null +++ b/src/sqlbuild/executor/python_nodes/classes/discovered_item_pool.py @@ -0,0 +1,278 @@ +"""Runs ready discovered items on threads, capped per set; only the calling thread records them.""" + +from __future__ import annotations + +import sys +from collections import Counter +from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait +from contextvars import copy_context +from dataclasses import replace +from threading import Lock +from time import monotonic +from typing import Any + +from sqlbuild._native import CommandTerminated, termination_requested +from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder +from sqlbuild.compiler.python_nodes.types import PythonNodeFanInAction, PythonNodeStatus +from sqlbuild.executor.node_results.main._direct_store import build_direct_node_result_store +from sqlbuild.executor.python_nodes._helpers.discovered_items import parallel_set +from sqlbuild.executor.python_nodes._helpers.results import evaluate_python_node_fan_in +from sqlbuild.executor.python_nodes.constants import ( + ABANDONABLE_THREAD_PREFIX, + ABANDONED_STEPS_NOTICE, + CANCEL_GRACE_SECONDS, + CANCEL_REPEAT_SECONDS, +) +from sqlbuild.executor.python_nodes.main._ready import run_ready_python_node +from sqlbuild.executor.python_nodes.models import ( + DiscoveredItemCallbacks, + ItemSlot, + PythonNodeExecutionResult, + PythonNodeFanInDecision, + PythonNodeRunState, + PythonNodeRuntime, + RunningItem, +) +from sqlbuild.executor.python_nodes.types import ExecutablePythonNode +from sqlbuild.runtime.execution_limits.main.cancel_running_statements import ( + cancel_running_statements, +) + + +class DiscoveredItemPool: + """One connection and result store per running item, each result recorded as it finishes.""" + + def __init__( + self, + *, + runtime: PythonNodeRuntime, + run_state: PythonNodeRunState, + callbacks: DiscoveredItemCallbacks, + ) -> None: + self._runtime: PythonNodeRuntime = runtime + self._run_state: PythonNodeRunState = run_state + self._callbacks: DiscoveredItemCallbacks = callbacks + self._write_lock: Lock = Lock() + self._idle: list[ItemSlot] = [] + self._opened: list[ItemSlot] = [] + self._running: dict[Future[PythonNodeExecutionResult], RunningItem] = {} + self._cancelled: bool = False + + def run(self, *, thread_limit: int) -> None: + """Run until no item is ready or running; only a cancel leaves a thread unjoined.""" + + threads: ThreadPoolExecutor = ThreadPoolExecutor( + max_workers=thread_limit, thread_name_prefix=ABANDONABLE_THREAD_PREFIX + ) + try: + try: + self._run_until_drained(threads) + except KeyboardInterrupt: + self._cancel() + raise + except BaseException: + self._finish_running() + raise + finally: + self._release(threads) + + def _run_until_drained(self, threads: ThreadPoolExecutor) -> None: + while True: + self._submit_ready(threads) + if not self._running: + return + done: set[Future[PythonNodeExecutionResult]] + done, _ = wait(self._running, return_when=FIRST_COMPLETED) + for future in [future for future in self._running if future in done]: + self._settle(future=future, result=future.result()) + + def _submit_ready(self, threads: ThreadPoolExecutor) -> None: + started: set[str] = {item.node.name for item in self._running.values()} + running_by_set: Counter[str] = Counter(item.set_name for item in self._running.values()) + node: ExecutablePythonNode + for node in self._callbacks.ready(): + if termination_requested(): + raise CommandTerminated("terminated by SIGTERM") + if node.name in started: + continue + limited: tuple[str, int] | None = parallel_set( + discovered=node.discovered, runtime=self._runtime + ) + if limited is None or running_by_set[limited[0]] >= limited[1]: + continue + upstream: tuple[PythonNodeExecutionResult, ...] = self._callbacks.upstream_results( + node.name + ) + slot: ItemSlot = self._take_slot() + future: Future[PythonNodeExecutionResult] = Future() + self._running[future] = RunningItem(node=node, set_name=limited[0], slot=slot) + started.add(node.name) + running_by_set[limited[0]] += 1 + self._report_start(node=node, upstream=upstream) + _ = threads.submit( + copy_context().run, + self._run_into, + future=future, + node=node, + upstream_results=upstream, + runtime=replace( + self._runtime, connection=slot.connection, result_store=slot.result_store + ), + statement_recorder=StatementRecorder(), + run_state=self._run_state, + ) + + @staticmethod + def _run_into( + *, + future: Future[PythonNodeExecutionResult], + **arguments: Any, + ) -> None: + """Run one item into `future`, tracked before it was submitted, unless it was cancelled.""" + + if not future.set_running_or_notify_cancel(): + return + try: + future.set_result(run_ready_python_node(**arguments)) + except BaseException as error: + future.set_exception(error) + + def _unstarted(self) -> list[RunningItem]: + """Take out each item no thread has begun; its cancelled future keeps one from beginning.""" + + return [self._running.pop(future) for future in list(self._running) if future.cancel()] + + def _report_start( + self, + *, + node: ExecutablePythonNode, + upstream: tuple[PythonNodeExecutionResult, ...], + ) -> None: + """Report that `node` has its slot, unless its upstream results keep it from running.""" + + if self._callbacks.started is None: + return + decision: PythonNodeFanInDecision = evaluate_python_node_fan_in(upstream_results=upstream) + if decision.action == PythonNodeFanInAction.RUN: + self._callbacks.started(node.name) + + def _settle( + self, + *, + future: Future[PythonNodeExecutionResult], + result: PythonNodeExecutionResult, + ) -> None: + """Record and report `result` while no item writes its own.""" + + item: RunningItem = self._running[future] + with self._write_lock: + self._callbacks.complete(node=item.node, result=result) + del self._running[future] + self._idle.append(item.slot) + + def _finish_running(self) -> None: + """After an error: start nothing more, and settle what is running as it returns.""" + + try: + _ = self._unstarted() + while self._running: + done: set[Future[PythonNodeExecutionResult]] + done, _ = wait(self._running, return_when=FIRST_COMPLETED) + for future in [future for future in self._running if future in done]: + if future.exception() is None: + self._settle(future=future, result=future.result()) + else: + del self._running[future] + except KeyboardInterrupt: + self._cancel() + raise + + def _cancel(self) -> None: + """Keep successes and report the rest cancelled, even if the cancel arrives again here.""" + + self._cancelled = True + deadline: float = monotonic() + CANCEL_GRACE_SECONDS + while True: + try: + self._report_until(deadline) + return + except CommandTerminated: + continue + + def _report_until(self, deadline: float) -> None: + """Report each item as it ends, those already done at `deadline` too, then the rest.""" + + for item in self._unstarted(): + self._report_cancelled(item) + while self._running: + cancel_running_statements() + done: set[Future[PythonNodeExecutionResult]] + done, _ = wait( + self._running, + timeout=max(0.0, min(CANCEL_REPEAT_SECONDS, deadline - monotonic())), + return_when=FIRST_COMPLETED, + ) + if not done and monotonic() >= deadline: + break + for future in [future for future in self._running if future in done]: + self._report_ended(future) + if not self._running: + return + steps: str = ", ".join(sorted(item.node.name for item in self._running.values())) + _ = sys.stderr.write( + ABANDONED_STEPS_NOTICE.format(steps=steps, seconds=CANCEL_GRACE_SECONDS) + ) + for item in self._running.values(): + self._report_cancelled(item) + + def _report_ended(self, future: Future[PythonNodeExecutionResult]) -> None: + """Report an ended item, its identity write neither blocking steps nor able to stop this.""" + + item: RunningItem = self._running[future] + if future.exception() is not None or future.result().status != PythonNodeStatus.SUCCESS: + self._report_cancelled(item) + elif item.node.name not in self._run_state.results_by_name: + try: + self._callbacks.complete(node=item.node, result=future.result()) + except (Exception, KeyboardInterrupt): + if item.node.name not in self._run_state.results_by_name: + raise + _ = self._running.pop(future, None) + + def _report_cancelled(self, item: RunningItem) -> None: + if self._callbacks.cancelled is not None: + self._callbacks.cancelled(item.node.name) + + def _take_slot(self) -> ItemSlot: + if self._idle: + return self._idle.pop() + runtime: PythonNodeRuntime = self._runtime + connection: Any = runtime.adapter.connect(dict(runtime.connection_config)) + result_store: Any | None = runtime.result_store + if result_store is None and runtime.persist_node_results: + result_store = build_direct_node_result_store( + adapter=runtime.adapter, + connection=connection, + database=runtime.default_database, + schema=runtime.default_schema, + target_config=runtime.target_config, + write_lock=self._write_lock, + ) + slot: ItemSlot = ItemSlot(connection=connection, result_store=result_store) + self._opened.append(slot) + return slot + + def _release(self, threads: ThreadPoolExecutor) -> None: + """Join and close; leave a cancelled step still running its slot and its providers.""" + + abandoned: bool = self._cancelled and bool(self._running) + if abandoned and self._runtime.providers is not None: + self._runtime.providers.leave_open() + threads.shutdown(wait=not abandoned) + held: list[ItemSlot] = [item.slot for item in self._running.values()] if abandoned else [] + slot: ItemSlot + for slot in self._opened: + if all(slot is not kept for kept in held): + self._runtime.adapter.close(slot.connection) + self._opened.clear() + self._idle.clear() diff --git a/src/sqlbuild/executor/python_nodes/classes/read_side_python_execution_tracker.py b/src/sqlbuild/executor/python_nodes/classes/read_side_python_execution_tracker.py index 3e15c2dbaa..c24aecccc4 100644 --- a/src/sqlbuild/executor/python_nodes/classes/read_side_python_execution_tracker.py +++ b/src/sqlbuild/executor/python_nodes/classes/read_side_python_execution_tracker.py @@ -2,13 +2,15 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import replace from typing import Any -from sqlbuild._native import CostContext, DiscoveredPythonNode, PythonNodeGraph +from sqlbuild._native import CostContext, DiscoveredPythonNode, PythonNodeGraph, output_node_scope from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder from sqlbuild.compiler.python_nodes.types import PythonNodeKind, PythonNodeStatus from sqlbuild.executor.node_results.main._direct_store import build_direct_node_result_store +from sqlbuild.executor.python_nodes._helpers.discovered_items import parallel_set from sqlbuild.executor.python_nodes._helpers.fingerprinting import ( try_write_python_node_identity_fingerprint, ) @@ -17,8 +19,10 @@ _sql_result_failed, _sql_result_name, ) +from sqlbuild.executor.python_nodes.classes.discovered_item_pool import DiscoveredItemPool from sqlbuild.executor.python_nodes.main._ready import run_ready_python_node from sqlbuild.executor.python_nodes.models import ( + DiscoveredItemCallbacks, PythonNodeExecutionResult, PythonNodeRunState, PythonNodeRuntime, @@ -40,12 +44,28 @@ def __init__( scheduled_sql_names: frozenset[str], runtime: PythonNodeRuntime, identity_recorder: PythonIdentityRecorder | None = None, + on_node_complete: Callable[[object], None] | None = None, + on_asset_start: Callable[[str], None] | None = None, + on_node_cancelled: Callable[[str], None] | None = None, ) -> None: self._python_graph: PythonNodeGraph = python_graph self._selected_python_names: frozenset[str] = selected_python_names self._scheduled_sql_names: frozenset[str] = scheduled_sql_names self._runtime: PythonNodeRuntime = runtime self._identity_recorder: PythonIdentityRecorder | None = identity_recorder + self._on_node_complete: Callable[[object], None] | None = on_node_complete + self._on_asset_start: Callable[[str], None] | None = on_asset_start + self._on_node_cancelled: Callable[[str], None] | None = on_node_cancelled + self._parallel: dict[str, tuple[str, int]] = {} + name: str + for name in selected_python_names: + selected: DiscoveredPythonNode = python_graph.nodes_by_name[name] + limited: tuple[str, int] | None = parallel_set( + discovered=None if selected.asset is None else selected.asset.discovered, + runtime=runtime, + ) + if limited is not None: + self._parallel[name] = limited self._result_store: Any | None = ( runtime.result_store if runtime.result_store is not None @@ -111,25 +131,65 @@ def record_sql_result(self, result: object) -> None: self.dispatch_ready_python_nodes() def dispatch_ready_python_nodes(self) -> None: - """Run all currently-ready selected Python nodes.""" + """Run every ready node, items with `max_parallel` side by side, reporting each at once.""" progressed: bool = True while progressed: progressed = False node_name: str for node_name in sorted(self._selected_python_names): - if node_name in self._completed_python_names: - continue - node: DiscoveredPythonNode = self._python_graph.nodes_by_name[node_name] - if node.kind != PythonNodeKind.ASSET: - continue - if not self._sql_dependencies_satisfied(node): + if not self._is_ready(node_name): continue - if not self._python_dependencies_satisfied(node): - continue - self._execute_python_node(node) + if node_name in self._parallel: + self._run_parallel_items() + else: + self._execute_python_node(self._python_graph.nodes_by_name[node_name]) progressed = True + def _is_ready(self, node_name: str) -> bool: + if node_name in self._completed_python_names: + return False + node: DiscoveredPythonNode = self._python_graph.nodes_by_name[node_name] + return ( + node.kind == PythonNodeKind.ASSET + and self._sql_dependencies_satisfied(node) + and self._python_dependencies_satisfied(node) + ) + + def _run_parallel_items(self) -> None: + DiscoveredItemPool( + runtime=self._runtime, + run_state=self._run_state, + callbacks=DiscoveredItemCallbacks( + ready=self._ready_items, + upstream_results=self._upstream_results, + complete=self._complete_item, + started=self._on_asset_start, + cancelled=self._on_node_cancelled, + ), + ).run(thread_limit=sum(dict(self._parallel.values()).values())) + + def _ready_items(self) -> tuple[ExecutablePythonNode, ...]: + return tuple( + _to_executable_python_node(self._python_graph.nodes_by_name[name]) + for name in sorted(self._parallel) + if self._is_ready(name) + ) + + def _complete_item( + self, *, node: ExecutablePythonNode, result: PythonNodeExecutionResult + ) -> None: + if self._on_node_complete is not None: + self._on_node_complete(result) + self._finalize_owned_result(node=node, result=result) + + def _upstream_results(self, node_name: str) -> tuple[PythonNodeExecutionResult, ...]: + return tuple( + self._results_by_name[upstream_name] + for upstream_name in self._python_graph.upstream_deps.get(node_name, ()) + if upstream_name in self._results_by_name + ) + def _sql_dependencies_satisfied(self, node: DiscoveredPythonNode) -> bool: sql_dep_name: str for sql_dep_name in (dependency.name for dependency in node.sql_deps): @@ -151,33 +211,36 @@ def _python_dependencies_satisfied(self, node: DiscoveredPythonNode) -> bool: return True def _execute_python_node(self, node: DiscoveredPythonNode) -> None: - runtime: PythonNodeRuntime = replace(self._runtime, result_store=self._result_store) - _ = run_ready_python_node( + runtime: PythonNodeRuntime = replace( + self._runtime, result_store=self._result_store, on_start=self._on_asset_start + ) + result: PythonNodeExecutionResult = run_ready_python_node( node=_to_executable_python_node(node), - upstream_results=tuple( - self._results_by_name[upstream_name] - for upstream_name in self._python_graph.upstream_deps.get(node.name, ()) - if upstream_name in self._results_by_name - ), + upstream_results=self._upstream_results(node.name), runtime=runtime, statement_recorder=StatementRecorder(), run_state=self._run_state, on_result=self._finalize_owned_result, ) + if self._on_node_complete is not None: + self._on_node_complete(result) def _finalize_owned_result( self, *, node: ExecutablePythonNode, result: PythonNodeExecutionResult ) -> None: discovered_node: DiscoveredPythonNode = self._python_graph.nodes_by_name[node.name] - self._run_state.record_result(node_function=discovered_node.function, result=result) + self._run_state.record_result(result=result) self._results_by_name[discovered_node.name] = result self._completed_python_names.add(discovered_node.name) if result.status != PythonNodeStatus.SUCCESS: return - with CostContext.resource_scope( - resource_type=discovered_node.kind.value, - resource_name=discovered_node.name, - phase="finalize", + with ( + output_node_scope(f"{discovered_node.kind.value}:{discovered_node.name}"), + CostContext.resource_scope( + resource_type=discovered_node.kind.value, + resource_name=discovered_node.name, + phase="finalize", + ), ): if self._identity_recorder is not None: self._identity_recorder(identity=discovered_node.identity, _target_name=None) diff --git a/src/sqlbuild/executor/python_nodes/classes/run_state.py b/src/sqlbuild/executor/python_nodes/classes/run_state.py index 36d7ce82c9..e0c785e60d 100644 --- a/src/sqlbuild/executor/python_nodes/classes/run_state.py +++ b/src/sqlbuild/executor/python_nodes/classes/run_state.py @@ -2,8 +2,6 @@ from __future__ import annotations -from collections.abc import Callable - from sqlbuild.executor.python_nodes.models import PythonNodeExecutionResult @@ -12,15 +10,11 @@ class PythonNodeRunState: def __init__( self, - results_by_function: dict[object, PythonNodeExecutionResult] | None = None, + results_by_name: dict[str, PythonNodeExecutionResult] | None = None, ) -> None: - self.results_by_function = results_by_function or {} + self.results_by_name = results_by_name or {} - def record_result( - self, - *, - node_function: Callable[..., object], - result: PythonNodeExecutionResult, - ) -> None: - self.results_by_function[node_function] = result - self.results_by_function[("name", result.node_name)] = result + def record_result(self, *, result: PythonNodeExecutionResult) -> None: + """Record `result` under its node's name, as the items of one asset share its function.""" + + self.results_by_name[result.node_name] = result diff --git a/src/sqlbuild/executor/python_nodes/constants.py b/src/sqlbuild/executor/python_nodes/constants.py index ab6a5eff1c..179600ee9f 100644 --- a/src/sqlbuild/executor/python_nodes/constants.py +++ b/src/sqlbuild/executor/python_nodes/constants.py @@ -4,3 +4,22 @@ MISSING_DEFAULT: object = object() PYTHON_NODE_RELATION_QUALIFIER_SEPARATOR: str = "." +ERROR_DETAIL_CHARS: int = 1900 +ERROR_SUMMARY_CHARS: int = 900 +ERROR_SUMMARY_CUT: str = "…\n" +TRACEBACK_HEADER: str = "Traceback (most recent call last):\n" +TRACEBACK_ELIDED: str = " ... {count} earlier lines\n" + +CANCEL_REPEAT_SECONDS: float = 1.0 +CANCEL_GRACE_SECONDS: float = 5.0 +ABANDONABLE_THREAD_PREFIX: str = "sqlbuild-item" +ABANDONED_STEPS_NOTICE: str = ( + "Stopped waiting for {steps} after {seconds:g} seconds; providers are left without teardown.\n" +) +MIN_PARALLEL_ITEMS: int = 2 +MEMORY_DATABASE: str = ":memory:" +CONNECTION_PRIVATE_MEMORY_DATABASE_KEYS: dict[str, str] = { + "duckdb": "database", + "motherduck": "database", + "sqlite": "path", +} diff --git a/src/sqlbuild/executor/python_nodes/main/exit_past_abandoned_steps.py b/src/sqlbuild/executor/python_nodes/main/exit_past_abandoned_steps.py new file mode 100644 index 0000000000..6590ebb8e5 --- /dev/null +++ b/src/sqlbuild/executor/python_nodes/main/exit_past_abandoned_steps.py @@ -0,0 +1,25 @@ +"""Public executor entrypoint to end a process whose cancelled step an exit would wait for.""" + +from __future__ import annotations + +import atexit +import os +import sys +import threading + +from sqlbuild.executor.python_nodes.constants import ABANDONABLE_THREAD_PREFIX + + +def exit_past_abandoned_steps(*, exit_code: int, last_line: str | None = None) -> None: + """End at once after the exit hooks and `last_line`, if an item's thread outlived its pool.""" + + if not any( + thread.name.startswith(ABANDONABLE_THREAD_PREFIX) for thread in threading.enumerate() + ): + return + atexit._run_exitfuncs() + _ = sys.stdout.flush() + if last_line is not None: + _ = sys.stderr.write(f"{last_line}\n") + _ = sys.stderr.flush() + os._exit(exit_code) diff --git a/src/sqlbuild/executor/python_nodes/main/read_side.py b/src/sqlbuild/executor/python_nodes/main/read_side.py index cc5613834c..8aca16f35b 100644 --- a/src/sqlbuild/executor/python_nodes/main/read_side.py +++ b/src/sqlbuild/executor/python_nodes/main/read_side.py @@ -2,6 +2,8 @@ from __future__ import annotations +from collections.abc import Callable + from sqlbuild._native import PythonNodeGraph from sqlbuild.executor.python_nodes.classes.read_side_python_execution_tracker import ( ReadSidePythonExecutionTracker, @@ -17,6 +19,9 @@ def create_read_side_python_execution_tracker( scheduled_sql_names: frozenset[str], runtime: PythonNodeRuntime, identity_recorder: PythonIdentityRecorder | None = None, + on_node_complete: Callable[[object], None] | None = None, + on_asset_start: Callable[[str], None] | None = None, + on_node_cancelled: Callable[[str], None] | None = None, ) -> ReadSidePythonExecutionTracker: """Create a read-side Python execution tracker.""" @@ -26,4 +31,7 @@ def create_read_side_python_execution_tracker( scheduled_sql_names=scheduled_sql_names, runtime=runtime, identity_recorder=identity_recorder, + on_node_complete=on_node_complete, + on_asset_start=on_asset_start, + on_node_cancelled=on_node_cancelled, ) diff --git a/src/sqlbuild/executor/python_nodes/models.py b/src/sqlbuild/executor/python_nodes/models.py index c74cbaf8fb..ce8808421f 100644 --- a/src/sqlbuild/executor/python_nodes/models.py +++ b/src/sqlbuild/executor/python_nodes/models.py @@ -10,7 +10,9 @@ from sqlbuild._native import TargetSettings from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.adapter.contract.classes.node_logger import NodeLogger from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder +from sqlbuild.adapter.contract.models import LifeCycleEvent from sqlbuild.adapter.relations.main.resolve_qualified_name_parts import ( resolve_qualified_name_parts, ) @@ -27,7 +29,11 @@ from sqlbuild.executor.python_nodes.constants import ( PYTHON_NODE_RELATION_QUALIFIER_SEPARATOR, ) -from sqlbuild.executor.python_nodes.types import PythonIdentityRecorder +from sqlbuild.executor.python_nodes.types import ( + ExecutablePythonNode, + OwnedResultCallback, + PythonIdentityRecorder, +) from sqlbuild.executor.scheduling.classes.session_warehouses import ( SessionWarehouses, configured_warehouse, @@ -105,6 +111,8 @@ class PythonNodeExecutionResult: skip_reason: str | None = None error_message: str | None = None warning_messages: tuple[str, ...] = field(default_factory=tuple) + error_detail: str | None = None + lifecycle_events: tuple[LifeCycleEvent, ...] = field(default_factory=tuple) @dataclass(frozen=True) @@ -153,6 +161,8 @@ class PythonNodeRuntime: persist_node_results: bool = True node_warehouses: Mapping[str, str] = field(default_factory=dict) session_warehouses: SessionWarehouses | None = None + chain_run_id: str | None = None + on_start: Callable[[str], None] | None = None def __post_init__(self) -> None: if self.node_warehouses and self.session_warehouses is None: @@ -178,7 +188,9 @@ class IngressCallbacks: use_color: bool = False on_node_start: NodeStartCallback | None = None + on_asset_start: Callable[[str], None] | None = None on_node_complete: Callable[[object], None] | None = None + on_node_cancelled: Callable[[str], None] | None = None identity_recorder: PythonIdentityRecorder | None = None @@ -222,9 +234,11 @@ def query(self, sql: str) -> Any: self.statement_recorder.record(sql) return self.adapter.execute(connection=self.connection, sql=sql) - def log(self, message: str) -> None: - self.statement_recorder.log(message) - self.logger.info(message) + @property + def log(self) -> NodeLogger: + """`ctx.log.info(...)`, `.warning(...)` or `.error(...)`, kept with the run's events.""" + + return NodeLogger(recorder=self.statement_recorder, logger=self.logger) def qualify_name( self, @@ -274,10 +288,28 @@ def skip( ) +@dataclass(frozen=True) +class DiscoveredContext: + """The discovered item an asset node runs for, and the tags its set was saved with.""" + + set: str + item: str + tags: Mapping[str, object] + + @dataclass(frozen=True, kw_only=True) class AssetContext(BasePythonNodeContext): """Runtime context passed to a SQLBuild asset function.""" + discovered: DiscoveredContext | None = None + chain_run_id: str | None = None + + @property + def root_run_id(self) -> str: + """The server run ID of the rerun chain's first run, or the local run's outside a worker.""" + + return self.chain_run_id or self.run_id + def result( self, *, @@ -350,3 +382,31 @@ class PythonCheckCallbacks: identity_recorder: PythonIdentityRecorder | None = None on_check_complete: Callable[[PythonCheckExecutionResult], None] | None = None on_check_start: Callable[[str], None] | None = None + + +@dataclass(frozen=True) +class ItemSlot: + """The warehouse connection and result store of one slot of a discovered item pool.""" + + connection: Any + result_store: Any | None + + +@dataclass(frozen=True) +class RunningItem: + """A discovered item on a thread, with its set and the slot it holds.""" + + node: ExecutablePythonNode + set_name: str + slot: ItemSlot + + +@dataclass(frozen=True) +class DiscoveredItemCallbacks: + """What a serial path gives its item pool; each is called only on the calling thread.""" + + ready: Callable[[], tuple[ExecutablePythonNode, ...]] + upstream_results: Callable[[str], tuple[PythonNodeExecutionResult, ...]] + complete: OwnedResultCallback + started: Callable[[str], None] | None = None + cancelled: Callable[[str], None] | None = None diff --git a/src/sqlbuild/executor/run/_helpers/execution/results.py b/src/sqlbuild/executor/run/_helpers/execution/results.py index 44c120fa46..193f1e57e7 100644 --- a/src/sqlbuild/executor/run/_helpers/execution/results.py +++ b/src/sqlbuild/executor/run/_helpers/execution/results.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging from dataclasses import replace from sqlbuild._native import ( @@ -15,6 +16,7 @@ format_waiting_on_empty_inputs, ) from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder +from sqlbuild.diagnostics.main.log_debug_event import log_debug_event from sqlbuild.executor.auditing.models import AuditExecutionResult from sqlbuild.executor.run.constants import ( RUN_AUDIT_FAILED_CODE, @@ -30,10 +32,17 @@ RUN_TYPE_ENFORCEMENT_FAILED_CODE, RUN_UNKNOWN_FAILED_CODE, ) -from sqlbuild.executor.run.models import HookExecutionResult, ModelExecutionResult +from sqlbuild.executor.run.models import ( + HookExecutionResult, + ModelExecutionResult, + ModelMaterializationContext, + TableTargets, +) from sqlbuild.executor.run.types import ExecutionPhase from sqlbuild.executor.scheduling.types import ExecutionStatus +_DEBUG_LOGGER: logging.Logger = logging.getLogger("sqlbuild.execution") + def build_failed_result( *, @@ -56,9 +65,11 @@ def build_failed_result( if error_prefix is not None: rendered_error = f"{error_prefix}: {rendered_error}" - statement_recorder.log(f"model {entry.name} failed phase={phase.value} error={rendered_error}") + statement_recorder.log( + message=f"model {entry.name} failed phase={phase.value} error={rendered_error}" + ) if staging_relation is not None: - statement_recorder.log(f"staging relation kept for inspection: {staging_relation}") + statement_recorder.log(message=f"staging relation kept for inspection: {staging_relation}") return ModelExecutionResult( model_name=entry.name, @@ -105,7 +116,7 @@ def build_skipped_result( """Build a skipped ModelExecutionResult after a lifecycle skip signal.""" skipped_hook: HookExecutionResult | None = _last_skipped_hook(hook_results) - statement_recorder.log(f"model {entry.name} skipped by hook") + statement_recorder.log(message=f"model {entry.name} skipped by hook") return ModelExecutionResult( model_name=entry.name, status=ExecutionStatus.SKIPPED, @@ -206,3 +217,29 @@ def with_waiting_on_empty_inputs_warning(result: ModelExecutionResult) -> ModelE if message in result.warning_messages: return result return replace(result, warning_messages=(*result.warning_messages, message)) + + +def rebuilt_table_rows( + *, context: ModelMaterializationContext, targets: TableTargets +) -> int | None: + """Exact rows of a freshly rebuilt table with no post-hooks; a failed read gives None.""" + + if context.entry.post_hooks: + return None + try: + return context.adapter.rebuilt_table_row_count( + connection=context.connection, + database=targets.target_database, + schema=targets.target_schema, + name=targets.target_table, + ) + except Exception as error: + log_debug_event( + logger=_DEBUG_LOGGER, + message="rebuilt table row count unavailable", + sqlbuild_subject="model", + sqlbuild_name=context.entry.name, + sqlbuild_event="row_count_unavailable", + sqlbuild_error_type=type(error).__name__, + ) + return None diff --git a/src/sqlbuild/executor/run/_helpers/validation/cursor_bounds.py b/src/sqlbuild/executor/run/_helpers/validation/cursor_bounds.py index cedbd9543f..dbd1bc9bed 100644 --- a/src/sqlbuild/executor/run/_helpers/validation/cursor_bounds.py +++ b/src/sqlbuild/executor/run/_helpers/validation/cursor_bounds.py @@ -35,6 +35,7 @@ cursor_window_override_flags, decide_empty_cursor_inputs, empty_input_rebuild_refusal, + replace_cursor_markers, resolve_cursor_intrinsics, ) from sqlbuild._native import cursor_clamp as clamp @@ -679,8 +680,11 @@ def substitute_cursor_sentinels(*, sql: str, bounds: CursorBounds) -> str: if sentinel_from_token(token=MICROBATCH_START_SENTINEL) is None: raise ExecutorInputError("invalid start cursor marker") - result: str = sql.replace(MICROBATCH_START_SENTINEL, sentinel_to_token(sentinel=bounds.start)) - result = result.replace(MICROBATCH_END_SENTINEL, sentinel_to_token(sentinel=bounds.end)) + result: str = replace_cursor_markers( + sql=sql, + start_sql=sentinel_to_token(sentinel=bounds.start), + end_sql=sentinel_to_token(sentinel=bounds.end), + ) _, has_intrinsics = resolve_cursor_intrinsics(sql=result) if has_intrinsics or MICROBATCH_START_SENTINEL in result or MICROBATCH_END_SENTINEL in result: raise ExecutorInputError("executable model SQL contains unresolved cursor markers") diff --git a/src/sqlbuild/executor/run/main/_execute.py b/src/sqlbuild/executor/run/main/_execute.py index fe13cbb17c..60527faef3 100644 --- a/src/sqlbuild/executor/run/main/_execute.py +++ b/src/sqlbuild/executor/run/main/_execute.py @@ -30,6 +30,7 @@ from sqlbuild.executor.run._helpers.execution.results import ( build_failed_result, build_skipped_result, + rebuilt_table_rows, ) from sqlbuild.executor.run._helpers.execution.results import ( with_waiting_on_empty_inputs_warning as with_waiting_on_empty_inputs_warning, @@ -381,6 +382,7 @@ def _staged_lifecycle( model_name=entry.name, status=ExecutionStatus.SUCCESS, promoted_relation=target_qualified, + table_rows=rebuilt_table_rows(context=context, targets=targets), audit_results=tuple(audit_results), warning_messages=tuple(warnings) + fingerprint_warnings, lifecycle_events=statement_recorder.snapshot(), @@ -510,6 +512,7 @@ def _immediate_lifecycle( model_name=entry.name, status=ExecutionStatus.SUCCESS, promoted_relation=target_qualified, + table_rows=rebuilt_table_rows(context=context, targets=targets), audit_results=tuple(audit_results), warning_messages=tuple(warnings) + fingerprint_warnings, lifecycle_events=statement_recorder.snapshot(), diff --git a/src/sqlbuild/executor/run/models.py b/src/sqlbuild/executor/run/models.py index cbcc004caa..ea94b71d23 100644 --- a/src/sqlbuild/executor/run/models.py +++ b/src/sqlbuild/executor/run/models.py @@ -32,6 +32,7 @@ from sqlbuild._native import cursor_compare as compare from sqlbuild._native import cursor_parse as parse from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.adapter.contract.classes.node_logger import NodeLogger from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder from sqlbuild.adapter.contract.models import LifeCycleEvent, QueryResult from sqlbuild.compiler.python_nodes.types import SkipMode @@ -133,8 +134,11 @@ def relation(self, ref: SqlResourceRef) -> str: self.relation_guard.record_resolved(ref) return relation - def log(self, message: str) -> None: - self.statement_recorder.log(message) + @property + def log(self) -> NodeLogger: + """`ctx.log.info(...)`, `.warning(...)` or `.error(...)`, kept with the run's events.""" + + return NodeLogger(recorder=self.statement_recorder, logger=None) def skip(self, *, reason: str, mode: SkipMode | str = SkipMode.SOFT) -> HookSkipResult: """Return a skip signal for the current hook.""" @@ -175,6 +179,7 @@ class ModelExecutionResult: batch_count: int | None = None batch_size: str | None = None rows_affected: int | None = None + table_rows: int | None = None cursor_range_start: str | None = None cursor_range_end: str | None = None cursor_type: str | None = None diff --git a/src/sqlbuild/executor/scenario/main/_cleanup.py b/src/sqlbuild/executor/scenario/main/_cleanup.py index 5253b6e441..f9ebf7d31f 100644 --- a/src/sqlbuild/executor/scenario/main/_cleanup.py +++ b/src/sqlbuild/executor/scenario/main/_cleanup.py @@ -88,7 +88,7 @@ def _execute_scenario_cleanup( statement_recorder=statement_recorder, ) except Exception as exc: - statement_recorder.log(f"scenario cleanup {scenario_plan.name} failed error={exc}") + statement_recorder.log(message=f"scenario cleanup {scenario_plan.name} failed error={exc}") return ScenarioCleanupExecutionResult( scenario_name=scenario_plan.name, status=ExecutionStatus.FAILED, diff --git a/src/sqlbuild/executor/scenario/main/_fixtures.py b/src/sqlbuild/executor/scenario/main/_fixtures.py index 7a03b0915e..4f2058c757 100644 --- a/src/sqlbuild/executor/scenario/main/_fixtures.py +++ b/src/sqlbuild/executor/scenario/main/_fixtures.py @@ -56,7 +56,7 @@ def execute_scenario_fixture( ) except Exception as exc: statement_recorder.log( - "scenario fixture " + message="scenario fixture " f"{scenario_name}:{fixture_plan.kind.value}:{fixture_plan.logical_name} " f"failed error={exc}" ) diff --git a/src/sqlbuild/executor/scheduling/_helpers/lifecycle.py b/src/sqlbuild/executor/scheduling/_helpers/lifecycle.py index 759592b894..a3a834e694 100644 --- a/src/sqlbuild/executor/scheduling/_helpers/lifecycle.py +++ b/src/sqlbuild/executor/scheduling/_helpers/lifecycle.py @@ -6,6 +6,8 @@ from sqlbuild.compiler.python_nodes.types import SkipMode from sqlbuild.errors.contracts.exceptions import ExecutorInputError +from sqlbuild.executor.scheduling.classes.lifecycle_concurrency import LifecycleConcurrency +from sqlbuild.executor.scheduling.classes.lifecycle_progress import LifecycleProgress from sqlbuild.executor.scheduling.models import ( LifecycleExecutionNode, LifecycleNodeResult, @@ -18,8 +20,9 @@ def run_lifecycle_scheduler( *, nodes: tuple[LifecycleExecutionNode, ...], handler: Callable[[LifecycleExecutionNode], LifecycleNodeResult], + concurrency: LifecycleConcurrency | None = None, ) -> LifecycleSchedulerResult: - """Run lifecycle nodes serially in topological order.""" + """Run lifecycle nodes serially in topological order, except those `concurrency` runs.""" node_by_name: dict[str, LifecycleExecutionNode] = {node.name: node for node in nodes} if len(node_by_name) != len(nodes): @@ -32,53 +35,54 @@ def run_lifecycle_scheduler( node_names=tuple(node.name for node in nodes), upstream_names=upstream_names, ) - in_degree: dict[str, int] = { - node_name: len(upstreams) for node_name, upstreams in upstream_names.items() - } - ready: list[str] = sorted(name for name, degree in in_degree.items() if degree == 0) - results_by_name: dict[str, LifecycleNodeResult] = {} - ordered_results: list[LifecycleNodeResult] = [] - - while ready: - node_name: str = ready.pop(0) - node: LifecycleExecutionNode = node_by_name[node_name] - dependency_result: LifecycleNodeResult | None = _blocking_dependency_result( - upstream_names=upstream_names[node_name], - results_by_name=results_by_name, - ) - if dependency_result is not None: - result: LifecycleNodeResult = LifecycleNodeResult( - name=node.name, - kind=node.kind, - status=LifecycleNodeStatus.SKIPPED, - skip_reason=_dependency_skip_reason(dependency_result), - skip_mode=SkipMode.HARD, - ) - elif _should_soft_skip_due_to_all_skipped_dependencies( - upstream_names=upstream_names[node_name], - results_by_name=results_by_name, - ): - result = LifecycleNodeResult( - name=node.name, - kind=node.kind, - status=LifecycleNodeStatus.SKIPPED, - skip_reason="All upstream nodes were skipped", - skip_mode=SkipMode.SOFT, - ) + progress: LifecycleProgress = LifecycleProgress( + node_by_name=node_by_name, + upstream_names=upstream_names, + downstream_names=downstream_names, + skip_result=_skip_result, + ) + while progress.ready: + node: LifecycleExecutionNode = node_by_name[progress.ready[0]] + skipped: LifecycleNodeResult | None = progress.skip(node) + if skipped is not None: + progress.complete(node=node, result=skipped) + elif concurrency is not None and concurrency.eligible(node): + concurrency.run(progress) else: - result = handler(node) - results_by_name[node.name] = result - ordered_results.append(result) - downstream_name: str - for downstream_name in downstream_names[node.name]: - in_degree[downstream_name] -= 1 - if in_degree[downstream_name] == 0: - ready.append(downstream_name) - ready.sort() - - if len(ordered_results) != len(nodes): + progress.complete(node=node, result=handler(node)) + + if len(progress.results) != len(nodes): raise ExecutorInputError("Lifecycle scheduler could not resolve all dependencies") - return LifecycleSchedulerResult(results=tuple(ordered_results)) + return LifecycleSchedulerResult(results=tuple(progress.results)) + + +def _skip_result( + *, node: LifecycleExecutionNode, results_by_name: dict[str, LifecycleNodeResult] +) -> LifecycleNodeResult | None: + """The result of a node its upstream results skip, or `None` when it runs.""" + + blocking: LifecycleNodeResult | None = _blocking_dependency_result( + upstream_names=node.upstream_names, results_by_name=results_by_name + ) + if blocking is not None: + return LifecycleNodeResult( + name=node.name, + kind=node.kind, + status=LifecycleNodeStatus.SKIPPED, + skip_reason=_dependency_skip_reason(blocking), + skip_mode=SkipMode.HARD, + ) + if _should_soft_skip_due_to_all_skipped_dependencies( + upstream_names=node.upstream_names, results_by_name=results_by_name + ): + return LifecycleNodeResult( + name=node.name, + kind=node.kind, + status=LifecycleNodeStatus.SKIPPED, + skip_reason="All upstream nodes were skipped", + skip_mode=SkipMode.SOFT, + ) + return None def _build_upstream_names( diff --git a/src/sqlbuild/executor/scheduling/classes/lifecycle_concurrency.py b/src/sqlbuild/executor/scheduling/classes/lifecycle_concurrency.py new file mode 100644 index 0000000000..ba21a4548f --- /dev/null +++ b/src/sqlbuild/executor/scheduling/classes/lifecycle_concurrency.py @@ -0,0 +1,21 @@ +"""How a lifecycle scheduler runs some of its nodes beside each other.""" + +from __future__ import annotations + +from collections.abc import Callable + +from sqlbuild.executor.scheduling.classes.lifecycle_progress import LifecycleProgress +from sqlbuild.executor.scheduling.models import LifecycleExecutionNode + + +class LifecycleConcurrency: + """Which ready nodes may run beside each other, and what runs them until none is ready.""" + + def __init__( + self, + *, + eligible: Callable[[LifecycleExecutionNode], bool], + run: Callable[[LifecycleProgress], None], + ) -> None: + self.eligible: Callable[[LifecycleExecutionNode], bool] = eligible + self.run: Callable[[LifecycleProgress], None] = run diff --git a/src/sqlbuild/executor/scheduling/classes/lifecycle_progress.py b/src/sqlbuild/executor/scheduling/classes/lifecycle_progress.py new file mode 100644 index 0000000000..a0972cb435 --- /dev/null +++ b/src/sqlbuild/executor/scheduling/classes/lifecycle_progress.py @@ -0,0 +1,73 @@ +"""What a lifecycle scheduler has finished, and which nodes that leaves ready.""" + +from __future__ import annotations + +from collections.abc import Callable + +from sqlbuild.executor.scheduling.models import LifecycleExecutionNode, LifecycleNodeResult + + +class LifecycleProgress: + """The scheduler's ready nodes and results; only the scheduler's thread uses it.""" + + def __init__( + self, + *, + node_by_name: dict[str, LifecycleExecutionNode], + upstream_names: dict[str, tuple[str, ...]], + downstream_names: dict[str, tuple[str, ...]], + skip_result: Callable[..., LifecycleNodeResult | None], + ) -> None: + self._node_by_name: dict[str, LifecycleExecutionNode] = node_by_name + self._downstream_names: dict[str, tuple[str, ...]] = downstream_names + self._skip_result: Callable[..., LifecycleNodeResult | None] = skip_result + self._in_degree: dict[str, int] = { + name: len(upstreams) for name, upstreams in upstream_names.items() + } + self._results_by_name: dict[str, LifecycleNodeResult] = {} + self.ready: list[str] = sorted( + name for name, degree in self._in_degree.items() if degree == 0 + ) + self.results: list[LifecycleNodeResult] = [] + + def skip(self, node: LifecycleExecutionNode) -> LifecycleNodeResult | None: + """The result of `node` when its upstream results skip it.""" + + return self._skip_result(node=node, results_by_name=self._results_by_name) + + def complete(self, *, node: LifecycleExecutionNode, result: LifecycleNodeResult) -> None: + """Record `result` once, as a cancel may offer it again, and ready what waited on `node`.""" + + if node.name not in self.ready: + return + self.ready.remove(node.name) + self._results_by_name[node.name] = result + self.results.append(result) + downstream_name: str + for downstream_name in self._downstream_names[node.name]: + self._in_degree[downstream_name] -= 1 + if self._in_degree[downstream_name] == 0: + self.ready.append(downstream_name) + self.ready.sort() + + def startable( + self, *, eligible: Callable[[LifecycleExecutionNode], bool] + ) -> tuple[LifecycleExecutionNode, ...]: + """The eligible ready nodes, once those their upstream results skip are recorded.""" + + while True: + candidates: list[LifecycleExecutionNode] = [] + skipped: bool = False + name: str + for name in tuple(self.ready): + node: LifecycleExecutionNode = self._node_by_name[name] + if not eligible(node): + continue + result: LifecycleNodeResult | None = self.skip(node) + if result is None: + candidates.append(node) + continue + self.complete(node=node, result=result) + skipped = True + if not skipped: + return tuple(candidates) diff --git a/src/sqlbuild/executor/scheduling/main/_run_lifecycle.py b/src/sqlbuild/executor/scheduling/main/_run_lifecycle.py index e42930aea0..61fadeb2c6 100644 --- a/src/sqlbuild/executor/scheduling/main/_run_lifecycle.py +++ b/src/sqlbuild/executor/scheduling/main/_run_lifecycle.py @@ -7,6 +7,7 @@ from sqlbuild.executor.scheduling._helpers.lifecycle import ( run_lifecycle_scheduler as _run_lifecycle_scheduler, ) +from sqlbuild.executor.scheduling.classes.lifecycle_concurrency import LifecycleConcurrency from sqlbuild.executor.scheduling.models import ( LifecycleExecutionNode, LifecycleNodeResult, @@ -18,7 +19,8 @@ def run_lifecycle_scheduler( *, nodes: tuple[LifecycleExecutionNode, ...], handler: Callable[[LifecycleExecutionNode], LifecycleNodeResult], + concurrency: LifecycleConcurrency | None = None, ) -> LifecycleSchedulerResult: - """Run lifecycle nodes serially in topological order.""" + """Run lifecycle nodes serially in topological order, except those `concurrency` runs.""" - return _run_lifecycle_scheduler(nodes=nodes, handler=handler) + return _run_lifecycle_scheduler(nodes=nodes, handler=handler, concurrency=concurrency) diff --git a/src/sqlbuild/playground_templates/waffle_shop/materializations/partition_tracked.py.txt b/src/sqlbuild/playground_templates/waffle_shop/materializations/partition_tracked.py.txt index 6f7487fa0c..b5360d4e9e 100644 --- a/src/sqlbuild/playground_templates/waffle_shop/materializations/partition_tracked.py.txt +++ b/src/sqlbuild/playground_templates/waffle_shop/materializations/partition_tracked.py.txt @@ -36,11 +36,11 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) if ctx.is_full_refresh: - ctx.log("clearing partition tracking state") + ctx.log.info("clearing partition tracking state") ctx.execute_sql(f"DELETE FROM {tracking_table}") all_partitions: list[str] = _generate_date_range(date_start, date_end) - ctx.log("checking for stale partitions") + ctx.log.info("checking for stale partitions") stale: list[str] = _find_stale_partitions(ctx, tracking_table, all_partitions) if not stale: @@ -68,7 +68,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: if ctx.on_progress is not None: ctx.on_progress(f"partition {i + 1}/{len(stale)}: {partition_value}") - ctx.log(f"building partition {partition_value}") + ctx.log.info(f"building partition {partition_value}") ctx.adapter.drop( connection=ctx.connection, @@ -95,7 +95,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) if not target_exists: - ctx.log("promoting first partition into target") + ctx.log.info("promoting first partition into target") ctx.adapter.rename( connection=ctx.connection, origin=staging, @@ -104,7 +104,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) target_exists = True else: - ctx.log("promoting partition into target") + ctx.log.info("promoting partition into target") ctx.execute_sql( f"DELETE FROM {ctx.destination} " f"WHERE CAST({partition_col} AS DATE) >= CAST('{partition_value}' AS DATE) " diff --git a/src/sqlbuild/provider/classes/container.py b/src/sqlbuild/provider/classes/container.py index ee53dd8677..6708c8d65e 100644 --- a/src/sqlbuild/provider/classes/container.py +++ b/src/sqlbuild/provider/classes/container.py @@ -35,6 +35,11 @@ def __contains__(self, name: object) -> bool: def __iter__(self) -> Iterator[str]: return iter(self.keys()) + def leave_open(self) -> None: + """Skip teardown, as a step that ignored a cancel may still use the providers.""" + + self._session.leave_open() + def keys(self) -> tuple[str, ...]: return self._session.keys() diff --git a/src/sqlbuild/provider/classes/session.py b/src/sqlbuild/provider/classes/session.py index 81462cb14d..79a4897d6d 100644 --- a/src/sqlbuild/provider/classes/session.py +++ b/src/sqlbuild/provider/classes/session.py @@ -40,6 +40,7 @@ def __init__( self._lifecycle_lock: RLock = RLock() self._close_holds: int = 0 self._close_requested: bool = False + self._left_open: bool = False self.teardown_error: ProviderTeardownError | None = None @property @@ -77,6 +78,8 @@ def get(self, name: str) -> Provider: f"Provider '{name}' was not found. Available providers: {available}" ) if name not in self._setup_names: + if self._is_closed: + raise ProviderLookupError(f"Provider session is closed; cannot set up '{name}'") self._setup_provider(name=name, provider=provider) return provider @@ -86,9 +89,16 @@ def hold_open(self) -> None: with self._lifecycle_lock: self._close_holds += 1 + def leave_open(self) -> None: + """Skip any teardown, even forced, while a step may use the providers; waits on no setup.""" + + self._left_open = True + def release(self) -> None: """Release an outer ownership hold and honor any deferred close request.""" + if self._left_open: + return should_close = False with self._lifecycle_lock: if self._close_holds < 1: @@ -99,6 +109,9 @@ def release(self) -> None: self.close() def close(self, *, force: bool = False) -> None: + if self._left_open: + self._is_closed = True + return with self._lifecycle_lock: if self._is_closed: return diff --git a/src/sqlbuild/python_nodes/_helpers/discovered_results.py b/src/sqlbuild/python_nodes/_helpers/discovered_results.py new file mode 100644 index 0000000000..d0ed30330c --- /dev/null +++ b/src/sqlbuild/python_nodes/_helpers/discovered_results.py @@ -0,0 +1,140 @@ +"""A discover function's items checked against the assets that run once per item, as JSON data.""" + +from __future__ import annotations + +import inspect +from collections.abc import Callable, Mapping, Sequence + +from sqlbuild._native import PythonNodeDiscoveryError +from sqlbuild.python_nodes.constants import CONTEXT_PARAMETER_NAMES, ITEM_DEPENDENCY_KIND +from sqlbuild.python_nodes.models import ( + Discovered, + DiscoveredItemRef, + Item, + NodeSetRef, + SqlResourceRef, +) +from sqlbuild.python_nodes.types import NodeSetKind, SqlResourceRefKind + + +def checked_items( + *, + returned: object, + functions: tuple[Callable[..., object], ...], + provider_names: frozenset[str], +) -> dict[str, object]: + """`returned` as the snapshot's JSON object; anything but a valid `Discovered` raises.""" + + if not isinstance(returned, Discovered): + raise PythonNodeDiscoveryError( + f"a @discover function must return Discovered(...), not {type(returned).__name__}" + ) + items: list[dict[str, object]] = [ + _item(item=item, functions=functions, provider_names=provider_names) + for item in returned.items + ] + payload: dict[str, object] = {"items": items, "tags": dict(returned.tags or {})} + if returned.max_parallel is not None: + payload["max_parallel"] = returned.max_parallel + return payload + + +def _item( + *, + item: object, + functions: tuple[Callable[..., object], ...], + provider_names: frozenset[str], +) -> dict[str, object]: + if not isinstance(item, Item): + raise PythonNodeDiscoveryError( + f"Discovered items must be Item(...), not {type(item).__name__}" + ) + args: dict[str, object] = dict(item.args) + for function in functions: + problem: str | None = _args_problem( + function=function, args=args, provider_names=provider_names + ) + if problem is not None: + raise PythonNodeDiscoveryError(f"item '{item.id}': {problem}") + return { + "id": item.id, + "depends_on": [_dependency(dependency) for dependency in item.depends_on], + "args": args, + } + + +def _dependency(dependency: object) -> object: + if isinstance(dependency, str): + return {ITEM_DEPENDENCY_KIND: dependency} + if isinstance(dependency, SqlResourceRef): + return {dependency.kind.value: dependency.name} + if isinstance(dependency, NodeSetRef): + return {dependency.kind.value: {"name": dependency.name, "exclude": dependency.exclude}} + raise PythonNodeDiscoveryError( + "an item depends on item IDs, model(), source(), seed(), job() or tag(), " + f"not {type(dependency).__name__}" + ) + + +def _args_problem( + *, function: Callable[..., object], args: dict[str, object], provider_names: frozenset[str] +) -> str | None: + """Why `args` cannot fill `function`'s parameters other than its context and providers.""" + + parameters: list[inspect.Parameter] = [ + parameter + for parameter in inspect.signature(function).parameters.values() + if parameter.kind not in {inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD} + ] + named_context: bool = any(parameter.name in CONTEXT_PARAMETER_NAMES for parameter in parameters) + if not named_context and parameters and parameters[0].name not in args: + parameters = parameters[1:] + fillable: list[inspect.Parameter] = [ + parameter + for parameter in parameters + if parameter.name not in CONTEXT_PARAMETER_NAMES and parameter.name not in provider_names + ] + names: set[str] = {parameter.name for parameter in fillable} + unknown: list[str] = sorted(set(args) - names) + function_name: str = str(getattr(function, "__name__", function)) + if unknown: + return f"{function_name} has no parameter {', '.join(unknown)}" + missing: list[str] = [ + parameter.name + for parameter in fillable + if parameter.default is inspect.Parameter.empty and parameter.name not in args + ] + if missing: + return f"args leave {function_name}'s {', '.join(missing)} unset" + return None + + +def item_dependency_refs( + *, depends_on: Sequence[Mapping[str, object]] +) -> tuple[DiscoveredItemRef | SqlResourceRef | NodeSetRef, ...]: + """Each saved `{"item": node}`, `{"model": name}` or `{"job": {...}}` as a node reference.""" + + return tuple(_reference(dependency) for dependency in depends_on) + + +def _reference( + dependency: Mapping[str, object], +) -> DiscoveredItemRef | SqlResourceRef | NodeSetRef: + ((kind, value),) = dependency.items() + sql_kinds: dict[str, SqlResourceRefKind] = { + member.value: member for member in SqlResourceRefKind + } + set_kinds: dict[str, NodeSetKind] = {member.value: member for member in NodeSetKind} + if kind == ITEM_DEPENDENCY_KIND: + return DiscoveredItemRef(name=str(value)) + if kind in sql_kinds: + return SqlResourceRef(kind=sql_kinds[kind], name=str(value)) + if kind in set_kinds and isinstance(value, Mapping): + fields: dict[str, object] = {str(key): item for key, item in value.items()} + exclude: object = fields.get("exclude") + return NodeSetRef( + kind=set_kinds[kind], + name=str(fields["name"]), + exclude=None if exclude is None else str(exclude), + ) + raise PythonNodeDiscoveryError(f"a discovered item cannot depend on {kind!r}") diff --git a/src/sqlbuild/python_nodes/constants.py b/src/sqlbuild/python_nodes/constants.py index 89bdee63df..dae0abace2 100644 --- a/src/sqlbuild/python_nodes/constants.py +++ b/src/sqlbuild/python_nodes/constants.py @@ -6,3 +6,6 @@ RELATION_RENDERER: ContextVar[Callable[[object], str] | None] = ContextVar( "sqlbuild_relation_renderer", default=None ) + +CONTEXT_PARAMETER_NAMES: frozenset[str] = frozenset({"ctx", "context", "_ctx", "hook_context"}) +ITEM_DEPENDENCY_KIND: str = "item" diff --git a/src/sqlbuild/python_nodes/main/apply_asset.py b/src/sqlbuild/python_nodes/main/apply_asset.py index 308482d44e..3c4e4c5a41 100644 --- a/src/sqlbuild/python_nodes/main/apply_asset.py +++ b/src/sqlbuild/python_nodes/main/apply_asset.py @@ -5,7 +5,7 @@ from collections.abc import Callable, Mapping, Sequence from typing import Any, cast -from sqlbuild._native import SourceColumnEntry +from sqlbuild._native import PythonNodeDiscoveryError, SourceColumnEntry from sqlbuild.python_nodes._helpers.attachment import attach_definition from sqlbuild.python_nodes._helpers.column_normalization import normalize_columns from sqlbuild.python_nodes._helpers.dependency_normalization import ( @@ -13,9 +13,11 @@ ) from sqlbuild.python_nodes._helpers.description_resolution import resolve_description from sqlbuild.python_nodes._helpers.lineage_normalization import normalize_column_lineage +from sqlbuild.python_nodes.main.read_discover_definition import read_discover_definition from sqlbuild.python_nodes.models import ( AssetDefinition, ColumnLineageRef, + DiscoverDefinition, NodeSetRef, RetryPolicy, SqlResourceRef, @@ -23,7 +25,7 @@ from sqlbuild.python_nodes.types import ColumnLineageRefSpec, PythonNodeColumnSpec -def apply_asset( +def apply_asset( # noqa: PLR0913 *, function: Callable[..., object] | None = None, name: str | None = None, @@ -39,9 +41,11 @@ def apply_asset( columns: Sequence[PythonNodeColumnSpec | SourceColumnEntry] = (), column_lineage: Mapping[str, Sequence[ColumnLineageRefSpec | ColumnLineageRef]] | None = None, retry: RetryPolicy | None = None, + for_each: Callable[..., object] | None = None, ) -> Callable[..., object] | Callable[[Callable[..., object]], Callable[..., object]]: """Apply SQLBuild asset metadata to a Python function.""" + discovered_by: str | None = _discover_name(for_each) normalized_deps: tuple[Callable[..., object] | SqlResourceRef | NodeSetRef, ...] = ( normalize_python_node_dependencies(depends_on) ) @@ -58,6 +62,7 @@ def decorate(inner: Callable[..., object]) -> Callable[..., object]: columns=normalize_columns(columns), column_lineage=normalize_column_lineage(column_lineage), retry=retry, + for_each=discovered_by, ) return attach_definition( function=inner, @@ -66,3 +71,14 @@ def decorate(inner: Callable[..., object]) -> Callable[..., object]: ) return decorate(function) if function is not None else decorate + + +def _discover_name(for_each: Callable[..., object] | None) -> str | None: + """The name of the discover function `for_each` names; anything else is refused.""" + + if for_each is None: + return None + definition: DiscoverDefinition | None = read_discover_definition(for_each) + if definition is None: + raise PythonNodeDiscoveryError("for_each takes a function decorated with @discover") + return definition.name diff --git a/src/sqlbuild/python_nodes/main/apply_discover.py b/src/sqlbuild/python_nodes/main/apply_discover.py new file mode 100644 index 0000000000..f117d97493 --- /dev/null +++ b/src/sqlbuild/python_nodes/main/apply_discover.py @@ -0,0 +1,28 @@ +"""Apply SQLBuild discover metadata to a Python function.""" + +from collections.abc import Callable +from typing import Any, cast + +from sqlbuild.python_nodes._helpers.attachment import attach_definition +from sqlbuild.python_nodes.models import DiscoverDefinition + + +def apply_discover( + *, + function: Callable[..., object] | None = None, + name: str | None = None, + check_every: str | None = None, +) -> Callable[..., object] | Callable[[Callable[..., object]], Callable[..., object]]: + """Mark a function as discovering a set of items in the location, at each publication.""" + + def decorate(inner: Callable[..., object]) -> Callable[..., object]: + inner_function: Any = cast(Any, inner) + return attach_definition( + function=inner, + attribute_name="__sqlbuild_discover__", + definition=DiscoverDefinition( + name=name or inner_function.__name__, check_every=check_every + ), + ) + + return decorate(function) if function is not None else decorate diff --git a/src/sqlbuild/python_nodes/main/discovered_result_json.py b/src/sqlbuild/python_nodes/main/discovered_result_json.py new file mode 100644 index 0000000000..2b3398fe98 --- /dev/null +++ b/src/sqlbuild/python_nodes/main/discovered_result_json.py @@ -0,0 +1,28 @@ +"""A discover function's `Discovered` return value as the JSON SQLBuild saves in the snapshot.""" + +from __future__ import annotations + +import json +from collections.abc import Callable + +from sqlbuild._native import PythonNodeDiscoveryError +from sqlbuild.python_nodes._helpers.discovered_results import checked_items + + +def discovered_result_json( + *, + returned: object, + functions: tuple[Callable[..., object], ...], + provider_names: frozenset[str], +) -> str: + """`returned` as JSON, each item's args checked against every `for_each` asset function.""" + + payload: dict[str, object] = checked_items( + returned=returned, functions=functions, provider_names=provider_names + ) + try: + return json.dumps(payload) + except TypeError as error: + raise PythonNodeDiscoveryError( + f"discovered args and tags must be JSON data: {error}" + ) from error diff --git a/src/sqlbuild/python_nodes/main/read_discover_definition.py b/src/sqlbuild/python_nodes/main/read_discover_definition.py new file mode 100644 index 0000000000..29d8f1f23a --- /dev/null +++ b/src/sqlbuild/python_nodes/main/read_discover_definition.py @@ -0,0 +1,16 @@ +"""Read SQLBuild discover metadata from a Python function.""" + +from collections.abc import Callable + +from sqlbuild.python_nodes._helpers.attachment import read_attached_definition +from sqlbuild.python_nodes.models import DiscoverDefinition + + +def read_discover_definition(function: Callable[..., object]) -> DiscoverDefinition | None: + """Return SQLBuild discover metadata from a decorated function, if present.""" + + return read_attached_definition( + function=function, + attribute_name="__sqlbuild_discover__", + definition_type=DiscoverDefinition, + ) diff --git a/src/sqlbuild/python_nodes/models.py b/src/sqlbuild/python_nodes/models.py index 85d5ccc712..2e2522bc28 100644 --- a/src/sqlbuild/python_nodes/models.py +++ b/src/sqlbuild/python_nodes/models.py @@ -120,6 +120,39 @@ class FactoryDefinition: name: str +@dataclass(frozen=True) +class DiscoverDefinition: + """Metadata attached to a function that discovers a set of items at publish.""" + + name: str + check_every: str | None = None + + +@dataclass(frozen=True) +class Item: + """One discovered item: its ID, the items or nodes it waits on, and its nodes' arguments.""" + + id: str + depends_on: tuple[str | SqlResourceRef | NodeSetRef, ...] = () + args: Mapping[str, object] = field(default_factory=dict) + + +@dataclass(frozen=True) +class Discovered: + """What a discover function returns: its items, and optional set-wide tags and parallelism.""" + + items: tuple[Item, ...] + tags: Mapping[str, object] | None = None + max_parallel: int | None = None + + +@dataclass(frozen=True) +class DiscoveredItemRef: + """A discovered item's dependency on another item of its set, by node name.""" + + name: str + + @dataclass(frozen=True) class AuditFactoryDefinition: """Metadata attached to an audit-case factory function.""" @@ -149,6 +182,7 @@ class AssetDefinition: columns: tuple[SourceColumnEntry, ...] = () column_lineage: dict[str, tuple[ColumnLineageRef, ...]] | None = None retry: RetryPolicy | None = None + for_each: str | None = None @dataclass(frozen=True) diff --git a/src/sqlbuild/runtime/execution_limits/_helpers/context.py b/src/sqlbuild/runtime/execution_limits/_helpers/context.py index e0a259cc6c..a149b7d89f 100644 --- a/src/sqlbuild/runtime/execution_limits/_helpers/context.py +++ b/src/sqlbuild/runtime/execution_limits/_helpers/context.py @@ -14,6 +14,10 @@ "sqlbuild_item_deadline", default=None, ) +current_bookkeeping_context: ContextVar[bool] = ContextVar( + "sqlbuild_bookkeeping_statements", + default=False, +) current_invocation_connections_context: ContextVar[ActiveConnections | None] = ContextVar( "sqlbuild_invocation_connections", default=None, diff --git a/src/sqlbuild/runtime/execution_limits/classes/active_connections.py b/src/sqlbuild/runtime/execution_limits/classes/active_connections.py index 89c387535d..70a652d01c 100644 --- a/src/sqlbuild/runtime/execution_limits/classes/active_connections.py +++ b/src/sqlbuild/runtime/execution_limits/classes/active_connections.py @@ -13,9 +13,22 @@ class ActiveConnections: def __init__(self) -> None: self._connections: dict[int, tuple[Any, Any, int]] = {} self._lock: threading.Lock = threading.Lock() + self._used: bool = False + + def activity(self) -> tuple[bool, bool]: + """Whether a statement has ever run here, and whether one runs now.""" + + return self._used, bool(self._connections) + + def note_used(self) -> None: + """Count a statement as run here without registering it for cancels.""" + + with self._lock: + self._used = True def add(self, *, adapter: Any, connection: Any) -> None: with self._lock: + self._used = True _, _, count = self._connections.get(id(connection), (adapter, connection, 0)) self._connections[id(connection)] = (adapter, connection, count + 1) diff --git a/src/sqlbuild/runtime/execution_limits/main/bookkeeping_statements.py b/src/sqlbuild/runtime/execution_limits/main/bookkeeping_statements.py new file mode 100644 index 0000000000..82795bfd38 --- /dev/null +++ b/src/sqlbuild/runtime/execution_limits/main/bookkeeping_statements.py @@ -0,0 +1,20 @@ +"""Mark a finished node's own writes, which a cancel or termination must not cut short.""" + +from __future__ import annotations + +from collections.abc import Generator +from contextlib import contextmanager +from contextvars import Token + +from sqlbuild.runtime.execution_limits._helpers.context import current_bookkeeping_context + + +@contextmanager +def bookkeeping_statements() -> Generator[None]: + """Keep the statements run inside out of what a cancel or termination cancels.""" + + token: Token[bool] = current_bookkeeping_context.set(True) + try: + yield + finally: + current_bookkeeping_context.reset(token) diff --git a/src/sqlbuild/runtime/execution_limits/main/_cancel_running_statements.py b/src/sqlbuild/runtime/execution_limits/main/cancel_running_statements.py similarity index 100% rename from src/sqlbuild/runtime/execution_limits/main/_cancel_running_statements.py rename to src/sqlbuild/runtime/execution_limits/main/cancel_running_statements.py diff --git a/src/sqlbuild/runtime/execution_limits/main/statement_activity.py b/src/sqlbuild/runtime/execution_limits/main/statement_activity.py new file mode 100644 index 0000000000..ba38d299c5 --- /dev/null +++ b/src/sqlbuild/runtime/execution_limits/main/statement_activity.py @@ -0,0 +1,11 @@ +"""Whether this process has run statements, and whether it runs one now.""" + +from __future__ import annotations + +from sqlbuild.runtime.execution_limits._helpers.running import running_statements + + +def statement_activity() -> tuple[bool, bool]: + """Whether a statement has ever run in this process, and whether one runs now.""" + + return running_statements.activity() diff --git a/src/sqlbuild/runtime/execution_limits/main/tracked_statement_connection.py b/src/sqlbuild/runtime/execution_limits/main/tracked_statement_connection.py index abeaaee289..7204a1519c 100644 --- a/src/sqlbuild/runtime/execution_limits/main/tracked_statement_connection.py +++ b/src/sqlbuild/runtime/execution_limits/main/tracked_statement_connection.py @@ -7,6 +7,7 @@ from typing import Any from sqlbuild.runtime.execution_limits._helpers.context import ( + current_bookkeeping_context, current_invocation_connections_context, current_item_deadline_context, ) @@ -17,9 +18,12 @@ @contextmanager def tracked_statement_connection(*, adapter: Any, connection: Any) -> Generator[None]: - """Record that a statement runs on `connection` so a deadline or termination can cancel it.""" + """Record a statement on `connection` for deadlines and, unless bookkeeping, for cancels.""" - registries: list[ActiveConnections] = [running_statements] + bookkeeping: bool = current_bookkeeping_context.get() + if bookkeeping: + running_statements.note_used() + registries: list[ActiveConnections] = [] if bookkeeping else [running_statements] invocation: ActiveConnections | None = current_invocation_connections_context.get() if invocation is not None: registries.append(invocation) diff --git a/tests/e2e/fixtures/waffle_shop/materializations/partition_tracked.py b/tests/e2e/fixtures/waffle_shop/materializations/partition_tracked.py index 11e7905415..719c077eee 100644 --- a/tests/e2e/fixtures/waffle_shop/materializations/partition_tracked.py +++ b/tests/e2e/fixtures/waffle_shop/materializations/partition_tracked.py @@ -36,11 +36,11 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) if ctx.is_full_refresh: - ctx.log("clearing partition tracking state") + ctx.log.info("clearing partition tracking state") ctx.execute_sql(f"DELETE FROM {tracking_table}") all_partitions: list[str] = _generate_date_range(date_start, date_end) - ctx.log("checking for stale partitions") + ctx.log.info("checking for stale partitions") stale: list[str] = _find_stale_partitions(ctx, tracking_table, all_partitions) if not stale: @@ -68,7 +68,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: if ctx.on_progress is not None: ctx.on_progress(f"partition {i + 1}/{len(stale)}: {partition_value}") - ctx.log(f"building partition {partition_value}") + ctx.log.info(f"building partition {partition_value}") ctx.adapter.drop( connection=ctx.connection, @@ -95,7 +95,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) if not target_exists: - ctx.log("promoting first partition into target") + ctx.log.info("promoting first partition into target") ctx.adapter.rename( connection=ctx.connection, origin=staging, @@ -104,7 +104,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) target_exists = True else: - ctx.log("promoting partition into target") + ctx.log.info("promoting partition into target") ctx.execute_sql( f"DELETE FROM {ctx.destination} " f"WHERE CAST({partition_col} AS DATE) >= CAST('{partition_value}' AS DATE) " diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py index 8defaec979..214337f048 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py @@ -1771,3 +1771,12 @@ class AdapterDefaultResultsFallbackE2ETestCase: kept_loader: str reading_task: str expected_payload_keys: tuple[str, str] + + +@dataclass(frozen=True) +class DiscoveredNodesE2ETestCase: + description: str + command: tuple[str, ...] + expected_exit_code: int + expected_output_patterns: tuple[str, ...] + expected_runs: tuple[str, ...] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py index d444000a5d..19954834f1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_compile_json_behavior.py @@ -194,7 +194,7 @@ def test_given_model_with_hooks_when_running_compile_json_then_it_reports_hook_m "from sqlbuild.hooks import hook\n\n" "@hook\n" "def notify(ctx, message):\n" - " '''Test hook notify.'''\n ctx.log(message)\n" + " '''Test hook notify.'''\n ctx.log.info(message)\n" ), "hooks/sql/select_value.sql": "HOOK (description 'Test hook select_value.');\n\nSELECT @value\n", "models/orders.sql": ( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py new file mode 100644 index 0000000000..3c4c749ece --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_discovered_nodes.py @@ -0,0 +1,216 @@ +"""Real-CLI coverage of discovered nodes outside a location: the placeholder, and `--discover`.""" + +from __future__ import annotations + +import re +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( + DiscoveredNodesE2ETestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb + +_PROJECT: str = ( + 'name = "discovered"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' + '[connection]\ndatabase = "discovered.duckdb"\n\n[targets.dev]\nschema = "dev"\n' +) +_NODES: str = '''\ +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import model + + +@discover +def plan() -> Discovered: + """Steps from an external plan.""" + return Discovered( + items=[Item(id="load", args={"step": "load"}), Item(id="fit", depends_on=("load",), args={"step": "fit"})], + tags={"release": "r1"}, + ) + + +@asset(for_each=plan, depends_on=model("orders")) +def run_step(ctx: AssetContext, step: str) -> None: + """Run one step.""" + with (Path(__file__).parents[2] / "runs.txt").open("a") as runs: + runs.write(f"{ctx.discovered.item}:{step}:{ctx.discovered.tags['release']}\\n") +''' + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoveredNodesE2ETestCase( + description="a plain build refuses the placeholder it cannot run", + command=("build",), + expected_exit_code=1, + expected_output_patterns=( + r"run_step is discovered at publish; run it from a location or `sqb dev`, " + r"or pass --discover", + ), + expected_runs=(), + ), + DiscoveredNodesE2ETestCase( + description="a build that selects the placeholder refuses it", + command=("build", "--select", "+run_step"), + expected_exit_code=1, + expected_output_patterns=( + r"run_step is discovered at publish; run it from a location or `sqb dev`, " + r"or pass --discover", + ), + expected_runs=(), + ), + DiscoveredNodesE2ETestCase( + description="a plain plan shows the placeholder", + command=("plan",), + expected_exit_code=0, + expected_output_patterns=(r"Plan ready", r"run_step\[\*\]"), + expected_runs=(), + ), + DiscoveredNodesE2ETestCase( + description="a plan that selects the asset shows the placeholder", + command=("plan", "--select", "+run_step"), + expected_exit_code=0, + expected_output_patterns=(r"Plan ready", r"run_step\[\*\]"), + expected_runs=(), + ), + DiscoveredNodesE2ETestCase( + description="--discover runs each item in order with its args and the set's tags", + command=("build", "--discover"), + expected_exit_code=0, + expected_output_patterns=(r"run_step\[load\]\s+OK", r"run_step\[fit\]\s+OK"), + expected_runs=("load:load:r1", "fit:fit:r1"), + ), + DiscoveredNodesE2ETestCase( + description="a bracketed selector names one item, and + its upstream items", + command=("build", "--discover", "--select", "+run_step[fit]"), + expected_exit_code=0, + expected_output_patterns=(r"run_step\[load\]\s+OK", r"run_step\[fit\]\s+OK"), + expected_runs=("load:load:r1", "fit:fit:r1"), + ), + DiscoveredNodesE2ETestCase( + description="the asset's name selects every item", + command=("build", "--discover", "--select", "asset:run_step"), + expected_exit_code=0, + expected_output_patterns=(r"run_step\[load\]\s+OK", r"run_step\[fit\]\s+OK"), + expected_runs=("load:load:r1", "fit:fit:r1"), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_for_each_asset_when_planning_or_building_outside_a_location_then_only_discover_runs_its_items( + tmp_path: Path, test_case: DiscoveredNodesE2ETestCase +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="discovered", + repo_files={ + "sqlbuild_project.toml": _PROJECT, + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _NODES, + }, + ) + runs_file: Path = project_dir / "runs.txt" + runs_file.touch() + result: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", *test_case.command), project_dir=project_dir + ) + output: str = result.stdout + result.stderr + + assert result.returncode == test_case.expected_exit_code, output + for pattern in test_case.expected_output_patterns: + assert re.search(pattern, output), output + assert tuple(runs_file.read_text().split()) == test_case.expected_runs + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoveredNodesE2ETestCase( + description="compile shows the placeholder, and --discover each item", + command=("compile", "--dag"), + expected_exit_code=0, + expected_output_patterns=(r'"asset:run_step\[\*\]"',), + expected_runs=('"asset:run_step[load]"', '"asset:run_step[fit]"'), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_for_each_asset_when_compiling_then_the_dag_shows_the_placeholder_or_the_items( + tmp_path: Path, test_case: DiscoveredNodesE2ETestCase +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="discovered", + repo_files={ + "sqlbuild_project.toml": _PROJECT, + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _NODES, + }, + ) + dag: Path = project_dir / "target" / "sqlbuild_dag.json" + + placeholder: subprocess.CompletedProcess[str] = run_sqb( + command=test_case.command, project_dir=project_dir + ) + placeholder_dag: str = dag.read_text() + discovered: subprocess.CompletedProcess[str] = run_sqb( + command=(*test_case.command, "--discover"), project_dir=project_dir + ) + discovered_dag: str = dag.read_text() + + assert (placeholder.returncode, discovered.returncode) == (test_case.expected_exit_code,) * 2 + for pattern in test_case.expected_output_patterns: + assert re.search(pattern, placeholder_dag), placeholder_dag + assert not re.search(pattern, discovered_dag), discovered_dag + for node in test_case.expected_runs: + assert node in discovered_dag, discovered_dag + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoveredNodesE2ETestCase( + description=f"{command} --discover stops on a set without items", + command=(command, "--discover"), + expected_exit_code=1, + expected_output_patterns=( + r"Discover function 'plan' failed: the discover function returned no items", + ), + expected_runs=(), + ) + for command in ("compile", "plan", "build") + ], + ids=lambda case: case.description, +) +def test_given_a_set_without_items_when_discovering_for_a_command_then_it_stops_with_the_error( + tmp_path: Path, test_case: DiscoveredNodesE2ETestCase +) -> None: + nodes: str = re.sub(r"items=\[.*\],", "items=[],", _NODES) + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="discovered", + repo_files={ + "sqlbuild_project.toml": _PROJECT, + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": nodes, + }, + ) + result: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", *test_case.command), project_dir=project_dir + ) + output: str = result.stdout + result.stderr + + assert result.returncode == test_case.expected_exit_code, output + for pattern in test_case.expected_output_patterns: + assert re.search(pattern, output), output + assert not (project_dir / "runs.txt").exists(), test_case.expected_runs + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py index 588c072fbe..88f6db4280 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_python_hooks.py @@ -828,7 +828,7 @@ def test_given_long_python_hook_name_when_building_then_cli_truncates_label_at_c "@hook\n" "def publish_customer_metadata_to_external_catalog_after_successful_" "materialization(ctx):\n" - ' """Test hook publish_customer_metadata_to_external_catalog_after_successful_materialization."""\n ctx.log("long hook ran")\n' + ' """Test hook publish_customer_metadata_to_external_catalog_after_successful_materialization."""\n ctx.log.info("long hook ran")\n' ), "models/orders.sql": ( "MODEL (description 'Test model orders.',\n" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py index a257732445..f859efd61e 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/_test_types.py @@ -147,6 +147,16 @@ class ProviderSecretE2ETestCase: unexpected_output_fragments: tuple[str, ...] = () +@dataclass(frozen=True) +class StrictPlanE2ETestCase: + description: str + select: str + extra_repo_files: dict[str, str] + # The text plan's "Can't run" block, empty when everything selected can run. + expected_block: str + expected_cant_run: list[dict[str, object]] + + @dataclass(frozen=True) class SharedSinkProviderE2ETestCase: description: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/helpers.py index 81e160d61d..dfe1ad19b8 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/helpers.py @@ -18,3 +18,8 @@ def linked_project(project_dir: Path) -> Path: def relative_project(project_dir: Path) -> Path: """The project relative to the directory sqb runs in.""" return Path(os.path.relpath(project_dir, REPO_ROOT)) + + +def blocked(entry: dict[str, object]) -> dict[str, object]: + """What a `cant_run` entry says can't run and why, without the file and env-file fields.""" + return {field: entry[field] for field in ("provider", "variables", "nodes", "readers", "sinks")} diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py index f39737e8d3..fcf0bcd574 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/providers/test_provider_secrets.py @@ -14,8 +14,10 @@ ProjectDirSpellingTestCase, ProviderCommandDiagnosticE2ETestCase, ProviderSecretE2ETestCase, + StrictPlanE2ETestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.providers.helpers import ( + blocked, linked_project, relative_project, ) @@ -156,6 +158,38 @@ def export_event(event: LifecycleEvent, api_provider: ApiProvider) -> None: '[targets.dev]\nschema = "main"\nallow_missing_secrets = ["api_provider"]\n' ), } +STRICT_TARGET: dict[str, str] = { + "sqlbuild_project.toml": ( + 'name = "provider_secret_project"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' + '[connection]\ndatabase = "provider_secret_project.duckdb"\n\n' + '[targets.dev]\nschema = "main"\n' + ), +} +SET_SECRET_VARIABLE: str = "SECRETS_E2E_SIGNING_KEY" +SET_SECRET_VALUE: str = "signing-key-canary" +# One secret is missing and one is set, and setting up the provider leaves a mark. +MARKING_PROVIDER: dict[str, str] = { + "providers/api.py": dedent( + f""" + import os + from pathlib import Path + + from pydantic import Field, SecretStr + from sqlbuild.providers import Provider + + + class ApiProvider(Provider): + '''Test provider ApiProvider.''' + api_key: SecretStr = Field(validation_alias="{SECRET_VARIABLE}") + signing_key: SecretStr = Field(validation_alias="{SET_SECRET_VARIABLE}") + + def setup(self, ctx): + with Path(os.environ["MARKER_PATH"]).open("a", encoding="utf-8") as marker: + marker.write("setup\\n") + """ + ).strip() + + "\n", +} REQUIRED_SETTING: dict[str, str] = { "providers/region.py": ( "from pydantic import Field\n" @@ -601,3 +635,88 @@ def test_given_a_changed_plan_when_a_secret_is_missing_then_only_nodes_it_runs_c assert changed["unchanged"] == test_case.expected_unchanged, planned.stdout assert [entry["nodes"] for entry in cant_run] == [test_case.expected_cant_run_nodes] assert [entry["readers"] for entry in cant_run] == [test_case.expected_cant_run_readers] + + +@pytest.mark.parametrize( + "test_case", + [ + StrictPlanE2ETestCase( + description="a selected node uses the provider", + select="+api_events", + extra_repo_files=READING_MODEL, + expected_block=( + f"Can't run: provider api_provider needs {SECRET_VARIABLE} " + "(missing from the environment and from .env)\n" + " needs raw_api_events, and api_events that read it\n" + ), + expected_cant_run=[ + { + "provider": "api_provider", + "variables": [SECRET_VARIABLE], + "nodes": ["source:raw_api_events"], + "readers": ["model:api_events"], + "sinks": [], + } + ], + ), + StrictPlanE2ETestCase( + description="only an unselected node uses the provider", + select="no_api", + extra_repo_files={}, + expected_block="", + expected_cant_run=[], + ), + StrictPlanE2ETestCase( + description="a sink uses the provider", + select="no_api", + extra_repo_files=API_SINK, + expected_block=( + f"Can't run: sink export_event needs {SECRET_VARIABLE}; every run uses sinks " + "(missing from the environment and from .env)\n" + ), + expected_cant_run=[ + { + "provider": "api_provider", + "variables": [SECRET_VARIABLE], + "nodes": [], + "readers": [], + "sinks": ["export_event"], + } + ], + ), + ], + ids=lambda case: case.description, +) +def test_given_a_strict_target_when_planning_without_a_secret_then_the_plan_lists_what_cant_run( + test_case: StrictPlanE2ETestCase, + tmp_path: Path, +) -> None: + marker_path: Path = tmp_path / "marker.log" + marker_path.write_text("", encoding="utf-8") + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="provider_secret_project", + repo_files={ + **PROJECT_FILES, + **STRICT_TARGET, + **MARKING_PROVIDER, + **test_case.extra_repo_files, + }, + ) + env: dict[str, str] = {"MARKER_PATH": str(marker_path), SET_SECRET_VARIABLE: SET_SECRET_VALUE} + plan: tuple[str, ...] = ("--no-color", "plan", "--select", test_case.select) + + text: subprocess.CompletedProcess[str] = run_sqb(command=plan, project_dir=project_dir, env=env) + as_json: subprocess.CompletedProcess[str] = run_sqb( + command=(*plan, "--json"), project_dir=project_dir, env=env + ) + + shown: str = text.stdout + text.stderr + as_json.stdout + as_json.stderr + assert (text.returncode, as_json.returncode) == (0, 0), shown + _, marked, block = text.stdout.partition("Can't run:") + assert marked + block == test_case.expected_block, shown + document: dict[str, object] = json.loads(as_json.stdout) + cant_run: list[dict[str, object]] = document.get("cant_run", []) # type: ignore[assignment] + assert [blocked(entry) for entry in cant_run] == test_case.expected_cant_run + assert SET_SECRET_VALUE not in shown + assert marker_path.read_text(encoding="utf-8") == "" diff --git a/tests/goldens/compiler/failure/provider-invalid-settings.json b/tests/goldens/compiler/failure/provider-invalid-settings.json index e86893d5f9..e067a82f9d 100644 --- a/tests/goldens/compiler/failure/provider-invalid-settings.json +++ b/tests/goldens/compiler/failure/provider-invalid-settings.json @@ -9,7 +9,7 @@ "severity": "error", "code": "D012", "message": "provider 'export_settings' (providers/export_settings.py) is missing secret API_TOKEN", - "help": "set API_TOKEN, or pass --allow-missing-secrets where secrets aren't available" + "help": "set API_TOKEN in this shell, or pass --allow-missing-secrets where secrets aren't available" } ] } diff --git a/tests/goldens/compiler/seed/0.json b/tests/goldens/compiler/seed/0.json index b93e0579c5..97606b604d 100644 --- a/tests/goldens/compiler/seed/0.json +++ b/tests/goldens/compiler/seed/0.json @@ -2,3863 +2,163 @@ "commands": [ { "label": "compile", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "P001", + "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + } + ] }, { "label": "compile-store-warm", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "P001", + "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + } + ] }, { "label": "plan", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + "Project discovery START", + "Project assembly START", + "Declaration parsing START", + "Declaration parsing OK ()", + "Python discovery START", + "Python discovery OK ()", + "Project assembly OK ()", + "Project discovery OK ()", + "Compiling project...", + "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "", + "" + ] }, { "label": "compile-select", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "P001", + "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + } + ] }, { "label": "compile-no-analysis", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "P001", + "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + } + ] }, { "label": "compile-rich-lineage", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "P001", + "message": "Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id" + } + ] }, { "label": "lineage-rich-upstream", - "exit_code": 0, - "diagnostics": [], - "stdout": { - "target": { - "resource_type": "model", - "resource_name": "cte_facts_stg_fulfillment_1", - "column_name": "amount" - }, - "direction": "upstream", - "metadata": { - "mode": "rich", - "max_depth": null, - "analyzed_models": 2, - "truncated": false - }, - "trace": [ - { - "source": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "cte_facts_stg_fulfillment_1", - "column_name": "amount" - }, - "transform": "direct", - "confidence": "high" - }, - { - "source": { - "resource_type": "source", - "resource_name": "raw_events_0", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "transform": "direct", - "confidence": "high" - } - ] - } + "exit_code": 1, + "diagnostics": [ + "Project discovery START", + "Project assembly START", + "Declaration parsing START", + "Declaration parsing OK ()", + "Python discovery START", + "Python discovery OK ()", + "Project assembly OK ()", + "Project discovery OK ()", + "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "", + "" + ], + "stdout": [ + "" + ] }, { "label": "lineage-rich-downstream", - "exit_code": 0, - "diagnostics": [], - "stdout": { - "target": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "direction": "downstream", - "metadata": { - "mode": "rich", - "max_depth": null, - "analyzed_models": 5, - "truncated": false - }, - "trace": [ - { - "source": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "cte_facts_stg_fulfillment_1", - "column_name": "amount" - }, - "transform": "direct", - "confidence": "high" - }, - { - "source": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "append_stg_fulfillment_1", - "column_name": "amount" - }, - "transform": "direct", - "confidence": "high" - }, - { - "source": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "fulfillment_summary_2", - "column_name": "amount" - }, - "transform": "direct", - "confidence": "high" - }, - { - "source": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "fulfillment_summary_2", - "column_name": "adjust_2_amount" - }, - "transform": "expression", - "confidence": "high" - }, - { - "source": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "bounded_stg_fulfillment_1", - "column_name": "amount" - }, - "transform": "direct", - "confidence": "high" - } - ] - } + "exit_code": 1, + "diagnostics": [ + "Project discovery START", + "Project assembly START", + "Declaration parsing START", + "Declaration parsing OK ()", + "Python discovery START", + "Python discovery OK ()", + "Project assembly OK ()", + "Project discovery OK ()", + "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "", + "" + ], + "stdout": [ + "" + ] }, { "label": "lineage-fast-upstream", - "exit_code": 0, - "diagnostics": [], - "stdout": { - "target": { - "resource_type": "model", - "resource_name": "cte_facts_stg_fulfillment_1", - "column_name": "amount" - }, - "direction": "upstream", - "metadata": { - "mode": "fast", - "max_depth": null, - "analyzed_models": 2, - "truncated": false - }, - "trace": [ - { - "source": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "cte_facts_stg_fulfillment_1", - "column_name": "amount" - }, - "transform": "cast", - "confidence": "high" - }, - { - "source": { - "resource_type": "source", - "resource_name": "raw_events_0", - "column_name": "amount" - }, - "target": { - "resource_type": "model", - "resource_name": "stg_fulfillment_1", - "column_name": "amount" - }, - "transform": "direct", - "confidence": "high" - } - ] - } + "exit_code": 1, + "diagnostics": [ + "Project discovery START", + "Project assembly START", + "Declaration parsing START", + "Declaration parsing OK ()", + "Python discovery START", + "Python discovery OK ()", + "Project assembly OK ()", + "Project discovery OK ()", + "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "", + "" + ], + "stdout": [ + "" + ] }, { "label": "lineage-relations", - "exit_code": 0, - "diagnostics": [], - "stdout": { - "nodes": [ - { - "id": "model:append_stg_fulfillment_1", - "name": "append_stg_fulfillment_1", - "resource_type": "model", - "relative_path": "models/features/append_stg_fulfillment_1.sql", - "qualified_name": "ci_checks.append_stg_fulfillment_1" - }, - { - "id": "model:bounded_stg_fulfillment_1", - "name": "bounded_stg_fulfillment_1", - "resource_type": "model", - "relative_path": "models/rendering/bounded_stg_fulfillment_1.sql", - "qualified_name": "ci_checks.bounded_stg_fulfillment_1" - }, - { - "id": "model:cte_facts_stg_fulfillment_1", - "name": "cte_facts_stg_fulfillment_1", - "resource_type": "model", - "relative_path": "models/analysis/cte_facts_stg_fulfillment_1.sql", - "qualified_name": "ci_checks.cte_facts_stg_fulfillment_1" - }, - { - "id": "model:fulfillment_summary_2", - "name": "fulfillment_summary_2", - "resource_type": "model", - "relative_path": "models/fulfillment/marts/fulfillment_summary_2.sql", - "qualified_name": "ci_checks.fulfillment_summary_2" - }, - { - "id": "model:stg_fulfillment_1", - "name": "stg_fulfillment_1", - "resource_type": "model", - "relative_path": "models/fulfillment/staging/stg_fulfillment_1.sql", - "qualified_name": "ci_checks.stg_fulfillment_1" - }, - { - "id": "source:raw_events_0", - "name": "raw_events_0", - "resource_type": "source", - "relative_path": "sources/raw.yml" - } - ], - "edges": [ - { - "from": "model:stg_fulfillment_1", - "to": "model:append_stg_fulfillment_1" - }, - { - "from": "model:stg_fulfillment_1", - "to": "model:bounded_stg_fulfillment_1" - }, - { - "from": "model:stg_fulfillment_1", - "to": "model:cte_facts_stg_fulfillment_1" - }, - { - "from": "model:stg_fulfillment_1", - "to": "model:fulfillment_summary_2" - }, - { - "from": "source:raw_events_0", - "to": "model:stg_fulfillment_1" - } - ], - "focus": [ - "model:stg_fulfillment_1" - ], - "direction": "both" - } + "exit_code": 1, + "diagnostics": [ + "Project discovery START", + "Project assembly START", + "Declaration parsing START", + "Declaration parsing OK ()", + "Python discovery START", + "Python discovery OK ()", + "Project assembly OK ()", + "Project discovery OK ()", + "error[P001]: Macro '@py.explode' in '/models/sales/staging/stg_sales_0.sql' failed: cannot adjust id", + "", + "" + ], + "stdout": [ + "" + ] } ], - "compiled": { - "audits/generic/configured_events/accepted_values__id.sql": [ - "SELECT id", - "FROM __source(\"configured_events\")", - "WHERE id IS NOT NULL", - " AND id NOT IN ('1')", - "" - ], - "audits/generic/configured_stg_sales_1/accepted_values__status.sql": [ - "SELECT status", - "FROM __ref(\"configured_stg_sales_1\")", - "WHERE status IS NOT NULL", - " AND status NOT IN ('placed', 'shipped')", - "" - ], - "audits/generic/configured_stg_sales_1/configured_amount_floor.sql": [ - "SELECT *", - "FROM __ref(\"configured_stg_sales_1\")", - "WHERE amount < -35", - "" - ], - "audits/generic/configured_stg_sales_1/configured_id_present__id.sql": [ - "SELECT id", - "FROM __ref(\"configured_stg_sales_1\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/configured_stg_sales_1/unique__id.sql": [ - "SELECT id, COUNT(*) AS duplicate_count", - "FROM __ref(\"configured_stg_sales_1\")", - "WHERE id IS NOT NULL", - "GROUP BY id", - "HAVING COUNT(*) > 1", - "" - ], - "audits/generic/fulfillment_summary_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"fulfillment_summary_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/labelled_stg_fulfillment_0/tidy_status__status.sql": [ - "SELECT *", - "FROM __ref(\"labelled_stg_fulfillment_0\")", - "WHERE status <> LOWER(TRIM(status))", - "" - ], - "audits/generic/sales_summary_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"sales_summary_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/sales_summary_2/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"sales_summary_2\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/shaped_stg_sales_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"shaped_stg_sales_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/stg_fulfillment_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"stg_fulfillment_0\")", - "WHERE id IS NULL", - "" - ], - "audits/singular/fulfillment_summary_2_matches.sql": [ - "SELECT a.id", - "FROM __ref(\"fulfillment_summary_2\") a", - "LEFT JOIN __ref(\"fulfillment_summary_0\") b ON a.id = b.id", - "WHERE b.id IS NULL", - "" - ], - "audits/singular/labelled_channels_match.sql": [ - "SELECT l.id", - "FROM __ref(\"labelled_stg_fulfillment_0\") l", - "JOIN __ref(\"channel_labels\") c ON l.id = c.id", - "WHERE l.status = c.channel", - "" - ], - "functions/python/is_large.sql": [ - "REGISTER PYTHON FUNCTION is_large(DOUBLE) RETURNS BOOLEAN", - "" - ], - "functions/sql/configured_label.sql": [ - "CREATE OR REPLACE MACRO ci_checks.configured_label(raw_status) AS (", - "UPPER(raw_status)", - ")", - "" - ], - "functions/sql/is_placed.sql": [ - "CREATE OR REPLACE MACRO ci_checks.is_placed(event_status) AS (", - "event_status = 'placed'", - ")", - "" - ], - "functions/sql/table_fn__events_above.sql": [ - "CREATE OR REPLACE MACRO ci_checks.table_fn__events_above(p_minimum) AS TABLE", - "SELECT id, amount", - "FROM __ref(\"stg_sales_1\")", - "WHERE amount > p_minimum", - "" - ], - "functions/sql/tidy_status.sql": [ - "CREATE OR REPLACE MACRO ci_checks.tidy_status(raw_status) AS (", - "LOWER(TRIM(raw_status))", - ")", - "" - ], - "models/analysis/cte_facts_stg_fulfillment_1.sql": [ - "WITH base AS (", - " SELECT id, CAST(amount AS DECIMAL(12, 2)) AS amount, 'event' AS kind,", - " COALESCE(status, 'unknown') AS status", - " FROM __ref(\"stg_fulfillment_1\")", - " WHERE id IS NOT NULL", - ")", - "SELECT id + 0 AS id, amount, UPPER(kind) AS kind, UPPER(status) AS status", - "FROM base", - "" - ], - "models/analysis/pivot_input_stg_sales_0.sql": [ - "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR) AS status, amount", - "FROM __ref(\"stg_sales_0\")", - "" - ], - "models/analysis/pivoted_stg_sales_0.sql": [ - "PIVOT __ref(\"pivot_input_stg_sales_0\")", - "ON status", - "USING MAX(amount)", - "GROUP BY id", - "" - ], - "models/analysis/regional_stg_fulfillment_0.sql": [ - "SELECT id, amount, 'east' AS region", - "FROM __ref(\"stg_fulfillment_0\")", - "" - ], - "models/analysis/unanalysed_stg_sales_0.sql": [ - "SELECT a.id, a.amount", - "FROM __ref(\"stg_sales_0\") AS a", - "JOIN __ref(\"stg_sales_0\") AS b NEAREST 1 BY DISTANCE abs(a.amount - b.amount)", - "" - ], - "models/features/append_stg_fulfillment_1.sql": [ - "SELECT id, amount, status, created_at", - "FROM __ref(\"stg_fulfillment_1\")", - "" - ], - "models/features/batched_rolling_window_stg_sales_0.sql": [ - "SELECT CAST(created_at AS DATE) AS created_at, SUM(amount) AS amount", - "FROM __ref(\"stg_sales_0\")", - "GROUP BY CAST(created_at AS DATE)", - "" - ], - "models/features/flagged_stg_fulfillment_0.sql": [ - "SELECT id, __udf(\"is_placed\")(status) AS is_placed,", - " __udf(\"is_large\")(amount) AS is_large", - "FROM __ref(\"stg_fulfillment_0\")", - "" - ], - "models/features/product_labels.sql": [ - "SELECT id, label", - "FROM __source(\"loaded_products\")", - "" - ], - "models/features/shaped_stg_sales_0.sql": [ - "SELECT CAST(id AS INTEGER) AS id, status", - "FROM __ref(\"stg_sales_0\")", - "" - ], - "models/features/taxed_stg_fulfillment_0.sql": [ - "SELECT id, ROUND(amount * 1.2, 2) AS taxed, ROUND(amount, 1) AS rounded", - "FROM __ref(\"stg_fulfillment_0\")", - "" - ], - "models/fulfillment/marts/fulfillment_summary_0.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " (t.amount * (1 - 0.1)) AS adjust_2_amount,", - " j2.label AS lookup_label_2,", - " 'naïve résumé' AS site_label", - "FROM __ref(\"stg_fulfillment_0\") t", - "LEFT JOIN __ref(\"stg_sales_0\") j1 ON t.id = j1.id", - "LEFT JOIN __seed(\"lookup_1\") j2 ON t.id = j2.id", - "" - ], - "models/fulfillment/marts/fulfillment_summary_1.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at", - "FROM __ref(\"stg_fulfillment_0\") t", - "" - ], - "models/fulfillment/marts/fulfillment_summary_2.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " (t.amount * (1 - 0.1)) AS adjust_2_amount,", - " j1.label AS lookup_label_1", - "FROM __ref(\"stg_fulfillment_1\") t", - "LEFT JOIN __seed(\"lookup_0\") j1 ON t.id = j1.id", - "" - ], - "models/fulfillment/staging/stg_fulfillment_0.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " 'naïve résumé' AS site_label", - "FROM __source(\"raw_events_1\") t", - "" - ], - "models/fulfillment/staging/stg_fulfillment_1.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " 'Ελληνικά orders' AS threshold_0_label,", - " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_0_amount,", - " 'naïve résumé' AS site_label", - "FROM __source(\"raw_events_0\") t", - "WHERE t.status <> 'expédié'", - "" - ], - "models/rendering/bounded_stg_fulfillment_1.sql": [ - "SELECT id, amount, created_at", - "FROM __ref(\"stg_fulfillment_1\")", - "WHERE created_at >= __cursor_start()", - " AND created_at < __cursor_end()", - "" - ], - "models/rendering/channel_labels.sql": [ - "SELECT id, channel", - "FROM __source(\"labelled_channels\")", - "" - ], - "models/rendering/configured_stg_sales_1.sql": [ - "SELECT id, amount, status", - "FROM __ref(\"stg_sales_1\")", - "" - ], - "models/rendering/labelled_stg_fulfillment_0.sql": [ - "SELECT id, LOWER(TRIM(status)) AS status,", - " __udf(\"tidy_status\")(status) AS tidied", - "FROM __ref(\"stg_fulfillment_0\")", - "" - ], - "models/rendering/large_events.sql": [ - "SELECT id, amount", - "FROM __table_fn(\"table_fn__events_above\")(4)", - "" - ], - "models/rendering/latest_raw_events_1.sql": [ - "SELECT id, amount", - "FROM (SELECT id, amount FROM __source(\"raw_events_1\") ORDER BY id DESC LIMIT 2) AS latest", - "" - ], - "models/rendering/unioned_event_ids.sql": [ - "SELECT id", - "FROM (SELECT id FROM __ref(\"stg_sales_0\") UNION ALL SELECT id FROM __ref(\"stg_sales_1\")) AS unioned", - "" - ], - "models/sales/marts/sales_summary_0.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " 'Ελληνικά orders' AS threshold_0_label,", - " j1.label AS lookup_label_1", - "FROM __ref(\"stg_sales_0\") t", - "LEFT JOIN __seed(\"lookup_1\") j1 ON t.id = j1.id", - "" - ], - "models/sales/marts/sales_summary_1.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " (t.amount * (1 - 0.1)) AS adjust_2_amount,", - " j1.label AS lookup_label_1", - "FROM __ref(\"stg_sales_0\") t", - "LEFT JOIN __seed(\"lookup_0\") j1 ON t.id = j1.id", - "WHERE t.status <> '取消'", - "" - ], - "models/sales/marts/sales_summary_2.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " 'naïve résumé' AS threshold_1_label,", - " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_0_amount,", - " j2.label AS lookup_label_2", - "FROM __ref(\"stg_sales_1\") t", - "LEFT JOIN __ref(\"stg_fulfillment_0\") j1 ON t.id = j1.id", - "LEFT JOIN __seed(\"lookup_1\") j2 ON t.id = j2.id", - "" - ], - "models/sales/staging/stg_sales_0.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount * '1e-07' AS threshold_2_amount,", - " 'naïve résumé' AS site_label", - "FROM __source(\"raw_events_0\") t", - "" - ], - "models/sales/staging/stg_sales_1.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " 'naïve résumé' AS threshold_1_label", - "FROM __source(\"raw_events_1\") t", - "" - ], - "tests/_chain_/labelled_stg_fulfillment_0__stg_fulfillment_0/test_labelled_stg_fulfillment_0.sql": [ - "WITH __source__raw_events_1 AS (SELECT 1 AS id, CAST(1 AS DOUBLE) AS amount, 'placed' AS status, TIMESTAMP '2026-01-01 00:00:00' AS created_at UNION ALL SELECT 2 AS id, CAST(2 AS DOUBLE) AS amount, 'placed' AS status, TIMESTAMP '2026-01-02 00:00:00' AS created_at),", - "__ref__stg_fulfillment_0 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " 'naïve résumé' AS site_label", - "FROM __source__raw_events_1 t),", - "__ref__labelled_stg_fulfillment_0 AS (SELECT id, LOWER(TRIM(status)) AS status,", - " ci_checks.tidy_status(status) AS tidied", - "FROM __ref__stg_fulfillment_0),", - "__actual__labelled_stg_fulfillment_0 AS (SELECT * FROM __ref__labelled_stg_fulfillment_0),", - "__expected__labelled_stg_fulfillment_0 AS (SELECT 1 AS id, LOWER(TRIM('placed')) AS status", - " UNION ALL", - " SELECT 2 AS id, 'placed' AS status)", - "SELECT 1 AS step_index, 'labelled_stg_fulfillment_0' AS model_name, (SELECT COUNT(*) FROM __actual__labelled_stg_fulfillment_0) AS actual_count, (SELECT COUNT(*) FROM __expected__labelled_stg_fulfillment_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __actual__labelled_stg_fulfillment_0 EXCEPT SELECT id, status FROM __expected__labelled_stg_fulfillment_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __expected__labelled_stg_fulfillment_0 EXCEPT SELECT id, status FROM __actual__labelled_stg_fulfillment_0) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/macro taxes_amounts/taxes_amounts.sql": [ - "WITH input_values AS (SELECT 10 AS amount),", - "__actual__macro_taxes_amounts AS (SELECT ROUND(amount * 1.2, 2) AS taxed", - " FROM input_values),", - "__expected__macro_taxes_amounts AS (SELECT 12.0 AS taxed)", - "SELECT 0 AS step_index, 'macro taxes_amounts' AS model_name, (SELECT COUNT(*) FROM __actual__macro_taxes_amounts) AS actual_count, (SELECT COUNT(*) FROM __expected__macro_taxes_amounts) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__macro_taxes_amounts EXCEPT SELECT * FROM __expected__macro_taxes_amounts) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__macro_taxes_amounts EXCEPT SELECT * FROM __actual__macro_taxes_amounts) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/regional_stg_fulfillment_0/test_regional_stg_fulfillment_0.sql": [ - "WITH __ref__stg_fulfillment_0 AS (SELECT 1 AS id, CAST(4 AS DOUBLE) AS amount, 'placed' AS status,", - " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__regional_stg_fulfillment_0 AS (SELECT id, amount, 'west' AS region", - "FROM __ref__stg_fulfillment_0),", - "__actual__regional_stg_fulfillment_0 AS (SELECT * FROM __ref__regional_stg_fulfillment_0),", - "__expected__regional_stg_fulfillment_0 AS (SELECT 1 AS id, CAST(4 AS DOUBLE) AS amount, 'west' AS region)", - "SELECT 0 AS step_index, 'regional_stg_fulfillment_0' AS model_name, (SELECT COUNT(*) FROM __actual__regional_stg_fulfillment_0) AS actual_count, (SELECT COUNT(*) FROM __expected__regional_stg_fulfillment_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, amount, region FROM __actual__regional_stg_fulfillment_0 EXCEPT SELECT id, amount, region FROM __expected__regional_stg_fulfillment_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, amount, region FROM __expected__regional_stg_fulfillment_0 EXCEPT SELECT id, amount, region FROM __actual__regional_stg_fulfillment_0) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/stg_fulfillment_1/test_stg_fulfillment_1.sql": [ - "WITH __source__raw_events_0 AS (SELECT 1 AS id, CAST(10 AS DOUBLE) AS amount, 'placed' AS status,", - " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__stg_fulfillment_1 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " 'Ελληνικά orders' AS threshold_0_label,", - " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_0_amount,", - " 'naïve résumé' AS site_label", - "FROM __source__raw_events_0 t", - "WHERE t.status <> 'expédié'),", - "__actual__stg_fulfillment_1 AS (SELECT * FROM __ref__stg_fulfillment_1),", - "__expected__stg_fulfillment_1 AS (SELECT 1 AS id, 'placed' AS status)", - "SELECT 0 AS step_index, 'stg_fulfillment_1' AS model_name, (SELECT COUNT(*) FROM __actual__stg_fulfillment_1) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_fulfillment_1) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __actual__stg_fulfillment_1 EXCEPT SELECT id, status FROM __expected__stg_fulfillment_1) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __expected__stg_fulfillment_1 EXCEPT SELECT id, status FROM __actual__stg_fulfillment_1) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/tests/unit/test_stg_sales_1_cases/block_1__labelled.sql": [ - "WITH __source__raw_events_1 AS (SELECT 1 AS id, CAST(2.25 AS DOUBLE) AS amount,", - " '東京 warehouse' AS status,", - " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__stg_sales_1 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " 'naïve résumé' AS threshold_1_label", - "FROM __source__raw_events_1 t),", - "__actual__stg_sales_1 AS (SELECT * FROM __ref__stg_sales_1),", - "__expected__stg_sales_1 AS (SELECT 1 AS id)", - "SELECT 0 AS step_index, 'stg_sales_1' AS model_name, (SELECT COUNT(*) FROM __actual__stg_sales_1) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_sales_1) AS expected_count, (SELECT COUNT(*) FROM (SELECT id FROM __actual__stg_sales_1 EXCEPT SELECT id FROM __expected__stg_sales_1) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id FROM __expected__stg_sales_1 EXCEPT SELECT id FROM __actual__stg_sales_1) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/tests/unit/test_stg_sales_1_cases/block_1__placed.sql": [ - "WITH __source__raw_events_1 AS (SELECT 1 AS id, CAST(1.5 AS DOUBLE) AS amount,", - " 'placed' AS status,", - " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__stg_sales_1 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " 'naïve résumé' AS threshold_1_label", - "FROM __source__raw_events_1 t),", - "__actual__stg_sales_1 AS (SELECT * FROM __ref__stg_sales_1),", - "__expected__stg_sales_1 AS (SELECT 1 AS id)", - "SELECT 0 AS step_index, 'stg_sales_1' AS model_name, (SELECT COUNT(*) FROM __actual__stg_sales_1) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_sales_1) AS expected_count, (SELECT COUNT(*) FROM (SELECT id FROM __actual__stg_sales_1 EXCEPT SELECT id FROM __expected__stg_sales_1) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id FROM __expected__stg_sales_1 EXCEPT SELECT id FROM __actual__stg_sales_1) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/udf detects_placed_events/detects_placed_events.sql": [ - "WITH input_values AS (SELECT 'placed' AS event_status),", - "__actual__udf_detects_placed_events AS (SELECT event_status, ci_checks.is_placed(event_status) AS is_placed", - " FROM input_values),", - "__expected__udf_detects_placed_events AS (SELECT 'placed' AS event_status, TRUE AS is_placed)", - "SELECT 0 AS step_index, 'udf detects_placed_events' AS model_name, (SELECT COUNT(*) FROM __actual__udf_detects_placed_events) AS actual_count, (SELECT COUNT(*) FROM __expected__udf_detects_placed_events) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__udf_detects_placed_events EXCEPT SELECT * FROM __expected__udf_detects_placed_events) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__udf_detects_placed_events EXCEPT SELECT * FROM __actual__udf_detects_placed_events) AS __sqlbuild_missing) AS missing_count", - "" - ] - }, - "manifest": { - "nodes": { - "model.generated_0.cte_facts_stg_fulfillment_1": { - "database": null, - "schema": "ci_checks", - "name": "cte_facts_stg_fulfillment_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/analysis/cte_facts_stg_fulfillment_1.sql", - "original_file_path": "models/analysis/cte_facts_stg_fulfillment_1.sql", - "unique_id": "model.generated_0.cte_facts_stg_fulfillment_1", - "fqn": [ - "generated_0", - "models", - "analysis", - "cte_facts_stg_fulfillment_1" - ], - "alias": "cte_facts_stg_fulfillment_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Contracted CTE reads of stg_fulfillment_1", - "columns": { - "id": { - "name": "id", - "description": "Recovered id", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "Recovered amount", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - }, - "kind": { - "name": "kind", - "description": "Recovered kind", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "Recovered status", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.cte_facts_stg_fulfillment_1", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_1" - ] - } - }, - "model.generated_0.pivot_input_stg_sales_0": { - "database": null, - "schema": "ci_checks", - "name": "pivot_input_stg_sales_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/analysis/pivot_input_stg_sales_0.sql", - "original_file_path": "models/analysis/pivot_input_stg_sales_0.sql", - "unique_id": "model.generated_0.pivot_input_stg_sales_0", - "fqn": [ - "generated_0", - "models", - "analysis", - "pivot_input_stg_sales_0" - ], - "alias": "pivot_input_stg_sales_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Contracted pivot input from stg_sales_0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.pivot_input_stg_sales_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_0" - ] - } - }, - "model.generated_0.pivoted_stg_sales_0": { - "database": null, - "schema": "ci_checks", - "name": "pivoted_stg_sales_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/analysis/pivoted_stg_sales_0.sql", - "original_file_path": "models/analysis/pivoted_stg_sales_0.sql", - "unique_id": "model.generated_0.pivoted_stg_sales_0", - "fqn": [ - "generated_0", - "models", - "analysis", - "pivoted_stg_sales_0" - ], - "alias": "pivoted_stg_sales_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Amounts of stg_sales_0 pivoted by status", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "dynamic_columns": [ - { - "name": "status_amounts", - "pivot_column": "status", - "value_column": "amount", - "aggregate": "MAX", - "type": "DOUBLE", - "name_pattern": null - } - ] - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.pivoted_stg_sales_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.pivot_input_stg_sales_0" - ] - } - }, - "model.generated_0.regional_stg_fulfillment_0": { - "database": null, - "schema": "ci_checks", - "name": "regional_stg_fulfillment_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/analysis/regional_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/regional_stg_fulfillment_0.sql", - "unique_id": "model.generated_0.regional_stg_fulfillment_0", - "fqn": [ - "generated_0", - "models", - "analysis", - "regional_stg_fulfillment_0" - ], - "alias": "regional_stg_fulfillment_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Regional copy of stg_fulfillment_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.regional_stg_fulfillment_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_0" - ] - } - }, - "model.generated_0.unanalysed_stg_sales_0": { - "database": null, - "schema": "ci_checks", - "name": "unanalysed_stg_sales_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/analysis/unanalysed_stg_sales_0.sql", - "original_file_path": "models/analysis/unanalysed_stg_sales_0.sql", - "unique_id": "model.generated_0.unanalysed_stg_sales_0", - "fqn": [ - "generated_0", - "models", - "analysis", - "unanalysed_stg_sales_0" - ], - "alias": "unanalysed_stg_sales_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Copy of stg_sales_0 that SQL analysis cannot parse", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.unanalysed_stg_sales_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_0" - ] - } - }, - "model.generated_0.append_stg_fulfillment_1": { - "database": null, - "schema": "ci_checks", - "name": "append_stg_fulfillment_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/features/append_stg_fulfillment_1.sql", - "original_file_path": "models/features/append_stg_fulfillment_1.sql", - "unique_id": "model.generated_0.append_stg_fulfillment_1", - "fqn": [ - "generated_0", - "models", - "features", - "append_stg_fulfillment_1" - ], - "alias": "append_stg_fulfillment_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "incremental", - "incremental_strategy": "append", - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Incremental append copy of stg_fulfillment_1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.append_stg_fulfillment_1", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_1" - ] - } - }, - "model.generated_0.batched_rolling_window_stg_sales_0": { - "database": null, - "schema": "ci_checks", - "name": "batched_rolling_window_stg_sales_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/features/batched_rolling_window_stg_sales_0.sql", - "original_file_path": "models/features/batched_rolling_window_stg_sales_0.sql", - "unique_id": "model.generated_0.batched_rolling_window_stg_sales_0", - "fqn": [ - "generated_0", - "models", - "features", - "batched_rolling_window_stg_sales_0" - ], - "alias": "batched_rolling_window_stg_sales_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "incremental", - "incremental_strategy": "delete_insert", - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Microbatched rolling_window totals of stg_sales_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.batched_rolling_window_stg_sales_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_0" - ] - } - }, - "model.generated_0.flagged_stg_fulfillment_0": { - "database": null, - "schema": "ci_checks", - "name": "flagged_stg_fulfillment_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/features/flagged_stg_fulfillment_0.sql", - "original_file_path": "models/features/flagged_stg_fulfillment_0.sql", - "unique_id": "model.generated_0.flagged_stg_fulfillment_0", - "fqn": [ - "generated_0", - "models", - "features", - "flagged_stg_fulfillment_0" - ], - "alias": "flagged_stg_fulfillment_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Function-flagged copy of stg_fulfillment_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.flagged_stg_fulfillment_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.is_placed", - "model.generated_0.is_large", - "model.generated_0.stg_fulfillment_0" - ] - } - }, - "model.generated_0.product_labels": { - "database": null, - "schema": "ci_checks", - "name": "product_labels", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/features/product_labels.sql", - "original_file_path": "models/features/product_labels.sql", - "unique_id": "model.generated_0.product_labels", - "fqn": [ - "generated_0", - "models", - "features", - "product_labels" - ], - "alias": "product_labels", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Product labels from the loader", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.product_labels", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_0.loaded_products" - ] - } - }, - "model.generated_0.shaped_stg_sales_0": { - "database": null, - "schema": "ci_checks", - "name": "shaped_stg_sales_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/features/shaped_stg_sales_0.sql", - "original_file_path": "models/features/shaped_stg_sales_0.sql", - "unique_id": "model.generated_0.shaped_stg_sales_0", - "fqn": [ - "generated_0", - "models", - "features", - "shaped_stg_sales_0" - ], - "alias": "shaped_stg_sales_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Schema-shaped copy of stg_sales_0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.shaped_stg_sales_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_0" - ] - } - }, - "model.generated_0.taxed_stg_fulfillment_0": { - "database": null, - "schema": "ci_checks", - "name": "taxed_stg_fulfillment_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/features/taxed_stg_fulfillment_0.sql", - "original_file_path": "models/features/taxed_stg_fulfillment_0.sql", - "unique_id": "model.generated_0.taxed_stg_fulfillment_0", - "fqn": [ - "generated_0", - "models", - "features", - "taxed_stg_fulfillment_0" - ], - "alias": "taxed_stg_fulfillment_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Taxed copy of stg_fulfillment_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.taxed_stg_fulfillment_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_0" - ] - } - }, - "model.generated_0.fulfillment_summary_0": { - "database": null, - "schema": "ci_checks", - "name": "fulfillment_summary_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_0.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_0.sql", - "unique_id": "model.generated_0.fulfillment_summary_0", - "fqn": [ - "generated_0", - "models", - "fulfillment", - "marts", - "fulfillment_summary_0" - ], - "alias": "fulfillment_summary_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Summary of fulfillment activity 0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.fulfillment_summary_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_0", - "model.generated_0.stg_sales_0", - "seed.generated_0.lookup_1" - ] - } - }, - "model.generated_0.fulfillment_summary_1": { - "database": null, - "schema": "ci_checks", - "name": "fulfillment_summary_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_1.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_1.sql", - "unique_id": "model.generated_0.fulfillment_summary_1", - "fqn": [ - "generated_0", - "models", - "fulfillment", - "marts", - "fulfillment_summary_1" - ], - "alias": "fulfillment_summary_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Summary of fulfillment activity 1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.fulfillment_summary_1", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_0" - ] - } - }, - "model.generated_0.fulfillment_summary_2": { - "database": null, - "schema": "ci_checks", - "name": "fulfillment_summary_2", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/fulfillment/marts/fulfillment_summary_2.sql", - "original_file_path": "models/fulfillment/marts/fulfillment_summary_2.sql", - "unique_id": "model.generated_0.fulfillment_summary_2", - "fqn": [ - "generated_0", - "models", - "fulfillment", - "marts", - "fulfillment_summary_2" - ], - "alias": "fulfillment_summary_2", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'ci_checks.fulfillment_summary_2' AS refreshed_relation, 'Zürich – depot' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'ci_checks.fulfillment_summary_2' AS refreshed", - "transaction": true, - "index": 1 - } - ], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Summary of fulfillment activity 2 (naïve résumé)", - "columns": {}, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'ci_checks.fulfillment_summary_2' AS refreshed_relation, 'Zürich – depot' AS refresh_label", - "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "Zürich – depot" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'ci_checks.fulfillment_summary_2' AS refreshed" - } - ] - } - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.fulfillment_summary_2", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_1", - "seed.generated_0.lookup_0" - ] - } - }, - "model.generated_0.stg_fulfillment_0": { - "database": null, - "schema": "ci_checks", - "name": "stg_fulfillment_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/fulfillment/staging/stg_fulfillment_0.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_0.sql", - "unique_id": "model.generated_0.stg_fulfillment_0", - "fqn": [ - "generated_0", - "models", - "fulfillment", - "staging", - "stg_fulfillment_0" - ], - "alias": "stg_fulfillment_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "staging" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "staging" - ], - "description": "Staged fulfillment events 0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.stg_fulfillment_0", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_0.raw_events_1" - ] - } - }, - "model.generated_0.stg_fulfillment_1": { - "database": null, - "schema": "ci_checks", - "name": "stg_fulfillment_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/fulfillment/staging/stg_fulfillment_1.sql", - "original_file_path": "models/fulfillment/staging/stg_fulfillment_1.sql", - "unique_id": "model.generated_0.stg_fulfillment_1", - "fqn": [ - "generated_0", - "models", - "fulfillment", - "staging", - "stg_fulfillment_1" - ], - "alias": "stg_fulfillment_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "staging" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "staging" - ], - "description": "Staged fulfillment events 1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.stg_fulfillment_1", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_0.raw_events_0" - ] - } - }, - "model.generated_0.bounded_stg_fulfillment_1": { - "database": null, - "schema": "ci_checks", - "name": "bounded_stg_fulfillment_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/rendering/bounded_stg_fulfillment_1.sql", - "original_file_path": "models/rendering/bounded_stg_fulfillment_1.sql", - "unique_id": "model.generated_0.bounded_stg_fulfillment_1", - "fqn": [ - "generated_0", - "models", - "rendering", - "bounded_stg_fulfillment_1" - ], - "alias": "bounded_stg_fulfillment_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "incremental", - "incremental_strategy": "delete_insert", - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": [ - "id" - ], - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Cursor-bounded copy of stg_fulfillment_1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.bounded_stg_fulfillment_1", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_fulfillment_1" - ] - } - }, - "model.generated_0.channel_labels": { - "database": null, - "schema": "ci_checks", - "name": "channel_labels", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/rendering/channel_labels.sql", - "original_file_path": "models/rendering/channel_labels.sql", - "unique_id": "model.generated_0.channel_labels", - "fqn": [ - "generated_0", - "models", - "rendering", - "channel_labels" - ], - "alias": "channel_labels", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Normalised channel labels", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.channel_labels", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_0.labelled_channels" - ] - } - }, - "model.generated_0.configured_stg_sales_1": { - "database": null, - "schema": "ci_checks", - "name": "configured_stg_sales_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/rendering/configured_stg_sales_1.sql", - "original_file_path": "models/rendering/configured_stg_sales_1.sql", - "unique_id": "model.generated_0.configured_stg_sales_1", - "fqn": [ - "generated_0", - "models", - "rendering", - "configured_stg_sales_1" - ], - "alias": "configured_stg_sales_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "release" - ], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "release" - ], - "description": "Configured copy of stg_sales_1 (réglé)", - "columns": { - "id": { - "name": "id", - "description": "Row key", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "Montant réglé", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.configured_stg_sales_1", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_1" - ] - } - }, - "model.generated_0.labelled_stg_fulfillment_0": { - "database": null, - "schema": "ci_checks", - "name": "labelled_stg_fulfillment_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/rendering/labelled_stg_fulfillment_0.sql", - "original_file_path": "models/rendering/labelled_stg_fulfillment_0.sql", - "unique_id": "model.generated_0.labelled_stg_fulfillment_0", - "fqn": [ - "generated_0", - "models", - "rendering", - "labelled_stg_fulfillment_0" - ], - "alias": "labelled_stg_fulfillment_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Labelled copy of stg_fulfillment_0", - "columns": { - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.labelled_stg_fulfillment_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.tidy_status", - "model.generated_0.stg_fulfillment_0" - ] - } - }, - "model.generated_0.large_events": { - "database": null, - "schema": "ci_checks", - "name": "large_events", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/rendering/large_events.sql", - "original_file_path": "models/rendering/large_events.sql", - "unique_id": "model.generated_0.large_events", - "fqn": [ - "generated_0", - "models", - "rendering", - "large_events" - ], - "alias": "large_events", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Events above a threshold from a table function", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.large_events", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.table_fn__events_above" - ] - } - }, - "model.generated_0.latest_raw_events_1": { - "database": null, - "schema": "ci_checks", - "name": "latest_raw_events_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/rendering/latest_raw_events_1.sql", - "original_file_path": "models/rendering/latest_raw_events_1.sql", - "unique_id": "model.generated_0.latest_raw_events_1", - "fqn": [ - "generated_0", - "models", - "rendering", - "latest_raw_events_1" - ], - "alias": "latest_raw_events_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Newest rows of raw_events_1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.latest_raw_events_1", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_0.raw_events_1" - ] - } - }, - "model.generated_0.unioned_event_ids": { - "database": null, - "schema": "ci_checks", - "name": "unioned_event_ids", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/rendering/unioned_event_ids.sql", - "original_file_path": "models/rendering/unioned_event_ids.sql", - "unique_id": "model.generated_0.unioned_event_ids", - "fqn": [ - "generated_0", - "models", - "rendering", - "unioned_event_ids" - ], - "alias": "unioned_event_ids", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Ids from two staged relations", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.unioned_event_ids", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_0", - "model.generated_0.stg_sales_1" - ] - } - }, - "model.generated_0.sales_summary_0": { - "database": null, - "schema": "ci_checks", - "name": "sales_summary_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_0.sql", - "original_file_path": "models/sales/marts/sales_summary_0.sql", - "unique_id": "model.generated_0.sales_summary_0", - "fqn": [ - "generated_0", - "models", - "sales", - "marts", - "sales_summary_0" - ], - "alias": "sales_summary_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "sales", - "marts" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'ci_checks.sales_summary_0' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'ci_checks.sales_summary_0' AS refreshed", - "transaction": true, - "index": 1 - } - ], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "sales", - "marts" - ], - "description": "Summary of sales activity 0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'ci_checks.sales_summary_0' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "Ελληνικά orders" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'ci_checks.sales_summary_0' AS refreshed" - } - ] - } - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.sales_summary_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_0", - "seed.generated_0.lookup_1" - ] - } - }, - "model.generated_0.sales_summary_1": { - "database": null, - "schema": "ci_checks", - "name": "sales_summary_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_1.sql", - "original_file_path": "models/sales/marts/sales_summary_1.sql", - "unique_id": "model.generated_0.sales_summary_1", - "fqn": [ - "generated_0", - "models", - "sales", - "marts", - "sales_summary_1" - ], - "alias": "sales_summary_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "sales", - "marts" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "sales", - "marts" - ], - "description": "Summary of sales activity 1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.sales_summary_1", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_0", - "seed.generated_0.lookup_0" - ] - } - }, - "model.generated_0.sales_summary_2": { - "database": null, - "schema": "ci_checks", - "name": "sales_summary_2", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/sales/marts/sales_summary_2.sql", - "original_file_path": "models/sales/marts/sales_summary_2.sql", - "unique_id": "model.generated_0.sales_summary_2", - "fqn": [ - "generated_0", - "models", - "sales", - "marts", - "sales_summary_2" - ], - "alias": "sales_summary_2", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "sales", - "marts" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "sales", - "marts" - ], - "description": "Summary of sales activity 2 (Ελληνικά orders)", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.sales_summary_2", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_0.stg_sales_1", - "model.generated_0.stg_fulfillment_0", - "seed.generated_0.lookup_1" - ] - } - }, - "model.generated_0.stg_sales_0": { - "database": null, - "schema": "ci_checks", - "name": "stg_sales_0", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/sales/staging/stg_sales_0.sql", - "original_file_path": "models/sales/staging/stg_sales_0.sql", - "unique_id": "model.generated_0.stg_sales_0", - "fqn": [ - "generated_0", - "models", - "sales", - "staging", - "stg_sales_0" - ], - "alias": "stg_sales_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "staging" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "staging" - ], - "description": "Staged sales events 0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.stg_sales_0", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_0.raw_events_0" - ] - } - }, - "model.generated_0.stg_sales_1": { - "database": null, - "schema": "ci_checks", - "name": "stg_sales_1", - "resource_type": "model", - "package_name": "generated_0", - "path": "models/sales/staging/stg_sales_1.sql", - "original_file_path": "models/sales/staging/stg_sales_1.sql", - "unique_id": "model.generated_0.stg_sales_1", - "fqn": [ - "generated_0", - "models", - "sales", - "staging", - "stg_sales_1" - ], - "alias": "stg_sales_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "staging" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "staging" - ], - "description": "Staged sales events 1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.stg_sales_1", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_0.raw_events_1" - ] - } - }, - "seed.generated_0.lookup_0": { - "database": null, - "schema": "ci_checks", - "name": "lookup_0", - "resource_type": "seed", - "package_name": "generated_0", - "path": "seeds/lookup_0.csv", - "original_file_path": "seeds/lookup_0.csv", - "unique_id": "seed.generated_0.lookup_0", - "fqn": [ - "generated_0", - "seeds", - "lookup_0" - ], - "alias": "lookup_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "seed", - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - }, - "delimiter": ",", - "quote_columns": null - }, - "tags": [], - "description": "Generated lookup 0.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "label": { - "name": "label", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.lookup_0", - "root_path": null, - "depends_on": { - "macros": [] - } - }, - "seed.generated_0.lookup_1": { - "database": null, - "schema": "ci_checks", - "name": "lookup_1", - "resource_type": "seed", - "package_name": "generated_0", - "path": "seeds/lookup_1.csv", - "original_file_path": "seeds/lookup_1.csv", - "unique_id": "seed.generated_0.lookup_1", - "fqn": [ - "generated_0", - "seeds", - "lookup_1" - ], - "alias": "lookup_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "seed", - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - }, - "delimiter": ",", - "quote_columns": null - }, - "tags": [], - "description": "Generated lookup 1.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "label": { - "name": "label", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.lookup_1", - "root_path": null, - "depends_on": { - "macros": [] - } - } - }, - "sources": { - "source.generated_0.configured_events": { - "database": null, - "schema": "", - "name": "configured_events", - "resource_type": "source", - "package_name": "generated_0", - "path": "sources/configured.yml", - "original_file_path": "sources/configured.yml", - "unique_id": "source.generated_0.configured_events", - "fqn": [ - "generated_0", - "configured_events" - ], - "source_name": "configured_events", - "source_description": "", - "loader": "", - "identifier": "configured_events", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Configured feed events", - "columns": { - "id": { - "name": "id", - "description": "Key id", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "owner": "orders team" - }, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_0.labelled_channels": { - "database": null, - "schema": "", - "name": "labelled_channels", - "resource_type": "source", - "package_name": "generated_0", - "path": "sources/labelled.yml", - "original_file_path": "sources/labelled.yml", - "unique_id": "source.generated_0.labelled_channels", - "fqn": [ - "generated_0", - "labelled_channels" - ], - "source_name": "labelled_channels", - "source_description": "", - "loader": "", - "identifier": "labelled_channels", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Channel labels normalised in the source expression.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "channel": { - "name": "channel", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_0.loaded_products": { - "database": null, - "schema": "ci_checks", - "name": "loaded_products", - "resource_type": "source", - "package_name": "generated_0", - "path": "sources/managed.yml", - "original_file_path": "sources/managed.yml", - "unique_id": "source.generated_0.loaded_products", - "fqn": [ - "generated_0", - "loaded_products" - ], - "source_name": "loaded_products", - "source_description": "", - "loader": "", - "identifier": "loaded_products", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Products loaded by a project loader.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "label": { - "name": "label", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "loader": "loaded_products", - "auto_load": false, - "write_strategy": "table" - } - }, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_0.raw_events_0": { - "database": null, - "schema": "", - "name": "raw_events_0", - "resource_type": "source", - "package_name": "generated_0", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", - "unique_id": "source.generated_0.raw_events_0", - "fqn": [ - "generated_0", - "raw_events_0" - ], - "source_name": "raw_events_0", - "source_description": "", - "loader": "", - "identifier": "raw_events_0", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Generated event feed 0.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - }, - "created_at": { - "name": "created_at", - "description": "", - "meta": {}, - "data_type": "TIMESTAMP", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_0.raw_events_1": { - "database": null, - "schema": "", - "name": "raw_events_1", - "resource_type": "source", - "package_name": "generated_0", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", - "unique_id": "source.generated_0.raw_events_1", - "fqn": [ - "generated_0", - "raw_events_1" - ], - "source_name": "raw_events_1", - "source_description": "", - "loader": "", - "identifier": "raw_events_1", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Generated event feed 1.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - }, - "created_at": { - "name": "created_at", - "description": "", - "meta": {}, - "data_type": "TIMESTAMP", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - } - }, - "macros": { - "macro.generated_0.adjust_0": { - "name": "adjust_0", - "resource_type": "macro", - "package_name": "generated_0", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", - "unique_id": "macro.generated_0.adjust_0", - "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", - "depends_on": { - "macros": [ - "macro.generated_0.adjust_0_round" - ] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.adjust_0_round": { - "name": "adjust_0_round", - "resource_type": "macro", - "package_name": "generated_0", - "path": "macros/python/adjust_0.py", - "original_file_path": "macros/python/adjust_0.py", - "unique_id": "macro.generated_0.adjust_0_round", - "macro_sql": "def adjust_0_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_0_round(f\"({expression} * 2)\")\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.adjust_2": { - "name": "adjust_2", - "resource_type": "macro", - "package_name": "generated_0", - "path": "macros/python/adjust_2.py", - "original_file_path": "macros/python/adjust_2.py", - "unique_id": "macro.generated_0.adjust_2", - "macro_sql": "def adjust_2(ctx, expression: str) -> str:\n \"\"\"Scale an amount by the configured discount.\"\"\"\n rate = ctx.vars[\"discount_rate\"]\n return f\"({expression} * (1 - {rate}))\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.tidy_label": { - "name": "tidy_label", - "resource_type": "macro", - "package_name": "generated_0", - "path": "macros/python/labels.py", - "original_file_path": "macros/python/labels.py", - "unique_id": "macro.generated_0.tidy_label", - "macro_sql": "def tidy_label(expression: str) -> str:\n \"\"\"Trim and lower-case a label.\"\"\"\n return f\"LOWER(TRIM({expression}))\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.round_amount": { - "name": "round_amount", - "resource_type": "macro", - "package_name": "generated_0", - "path": "macros/python/rounding.py", - "original_file_path": "macros/python/rounding.py", - "unique_id": "macro.generated_0.round_amount", - "macro_sql": "def round_amount(expression: str, places: int = 2) -> str:\n \"\"\"Round an amount.\"\"\"\n return f\"ROUND({expression}, {places})\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.taxed": { - "name": "taxed", - "resource_type": "macro", - "package_name": "generated_0", - "path": "macros/python/tax.py", - "original_file_path": "macros/python/tax.py", - "unique_id": "macro.generated_0.taxed", - "macro_sql": "from macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", - "depends_on": { - "macros": [ - "macro.generated_0.round_amount" - ] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.analysis_region": { - "name": "analysis_region", - "resource_type": "macro", - "package_name": "generated_0", - "path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", - "unique_id": "macro.generated_0.analysis_region", - "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'east'\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/analysis" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.adjust_1": { - "name": "adjust_1", - "resource_type": "macro", - "package_name": "generated_0", - "path": "models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", - "original_file_path": "models/fulfillment/staging/_sqlbuild/_macros/python/adjust_1.py", - "unique_id": "macro.generated_0.adjust_1", - "macro_sql": "import os\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Tag an amount with the deployment region.\"\"\"\n region = os.environ.get(\"SQB_DIFFERENTIAL_REGION\", \"east\")\n return f\"({expression} + LENGTH('{region}'))\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/fulfillment/staging" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.latest_rows": { - "name": "latest_rows", - "resource_type": "macro", - "package_name": "generated_0", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "unique_id": "macro.generated_0.latest_rows", - "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.union_ids": { - "name": "union_ids", - "resource_type": "macro", - "package_name": "generated_0", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "unique_id": "macro.generated_0.union_ids", - "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0.event_rows": { - "name": "event_rows", - "resource_type": "macro", - "package_name": "generated_0", - "path": "tests/unit/rendering/_sqlbuild/_macros/python/fixtures.py", - "original_file_path": "tests/unit/rendering/_sqlbuild/_macros/python/fixtures.py", - "unique_id": "macro.generated_0.event_rows", - "macro_sql": "def event_rows(count: int = 2) -> str:\n \"\"\"Return fixture event rows.\"\"\"\n return \" UNION ALL \".join(\n f\"SELECT {index} AS id, CAST({index} AS DOUBLE) AS amount, \"\n f\"'placed' AS status, \"\n f\"TIMESTAMP '2026-01-0{index} 00:00:00' AS created_at\"\n for index in range(1, count + 1)\n )\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "tests/unit/rendering" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_0__sqlbuild_hooks.record_refresh": { - "name": "record_refresh", - "resource_type": "macro", - "package_name": "generated_0__sqlbuild_hooks", - "path": "hooks/sql/record_refresh.sql", - "original_file_path": "hooks/sql/record_refresh.sql", - "unique_id": "macro.generated_0__sqlbuild_hooks.record_refresh", - "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "depends_on": { - "macros": [] - }, - "description": "Record a refresh for one relation", - "meta": { - "sqlbuild_resource_type": "sql_hook", - "sqlbuild_hook_name": "record_refresh" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - } - }, - "exposures": {}, - "metrics": {}, - "groups": {}, - "selectors": {}, - "disabled": {}, - "parent_map": { - "model.generated_0.cte_facts_stg_fulfillment_1": [ - "model.generated_0.stg_fulfillment_1" - ], - "model.generated_0.pivot_input_stg_sales_0": [ - "model.generated_0.stg_sales_0" - ], - "model.generated_0.pivoted_stg_sales_0": [ - "model.generated_0.pivot_input_stg_sales_0" - ], - "model.generated_0.regional_stg_fulfillment_0": [ - "model.generated_0.stg_fulfillment_0" - ], - "model.generated_0.unanalysed_stg_sales_0": [ - "model.generated_0.stg_sales_0" - ], - "model.generated_0.append_stg_fulfillment_1": [ - "model.generated_0.stg_fulfillment_1" - ], - "model.generated_0.batched_rolling_window_stg_sales_0": [ - "model.generated_0.stg_sales_0" - ], - "model.generated_0.flagged_stg_fulfillment_0": [ - "model.generated_0.is_placed", - "model.generated_0.is_large", - "model.generated_0.stg_fulfillment_0" - ], - "model.generated_0.product_labels": [ - "source.generated_0.loaded_products" - ], - "model.generated_0.shaped_stg_sales_0": [ - "model.generated_0.stg_sales_0" - ], - "model.generated_0.taxed_stg_fulfillment_0": [ - "model.generated_0.stg_fulfillment_0" - ], - "model.generated_0.fulfillment_summary_0": [ - "model.generated_0.stg_fulfillment_0", - "model.generated_0.stg_sales_0", - "seed.generated_0.lookup_1" - ], - "model.generated_0.fulfillment_summary_1": [ - "model.generated_0.stg_fulfillment_0" - ], - "model.generated_0.fulfillment_summary_2": [ - "model.generated_0.stg_fulfillment_1", - "seed.generated_0.lookup_0" - ], - "model.generated_0.stg_fulfillment_0": [ - "source.generated_0.raw_events_1" - ], - "model.generated_0.stg_fulfillment_1": [ - "source.generated_0.raw_events_0" - ], - "model.generated_0.bounded_stg_fulfillment_1": [ - "model.generated_0.stg_fulfillment_1" - ], - "model.generated_0.channel_labels": [ - "source.generated_0.labelled_channels" - ], - "model.generated_0.configured_stg_sales_1": [ - "model.generated_0.stg_sales_1" - ], - "model.generated_0.labelled_stg_fulfillment_0": [ - "model.generated_0.tidy_status", - "model.generated_0.stg_fulfillment_0" - ], - "model.generated_0.large_events": [ - "model.generated_0.table_fn__events_above" - ], - "model.generated_0.latest_raw_events_1": [ - "source.generated_0.raw_events_1" - ], - "model.generated_0.unioned_event_ids": [ - "model.generated_0.stg_sales_0", - "model.generated_0.stg_sales_1" - ], - "model.generated_0.sales_summary_0": [ - "model.generated_0.stg_sales_0", - "seed.generated_0.lookup_1" - ], - "model.generated_0.sales_summary_1": [ - "model.generated_0.stg_sales_0", - "seed.generated_0.lookup_0" - ], - "model.generated_0.sales_summary_2": [ - "model.generated_0.stg_sales_1", - "model.generated_0.stg_fulfillment_0", - "seed.generated_0.lookup_1" - ], - "model.generated_0.stg_sales_0": [ - "source.generated_0.raw_events_0" - ], - "model.generated_0.stg_sales_1": [ - "source.generated_0.raw_events_1" - ], - "source.generated_0.configured_events": [], - "source.generated_0.labelled_channels": [], - "source.generated_0.loaded_products": [], - "source.generated_0.raw_events_0": [], - "source.generated_0.raw_events_1": [], - "seed.generated_0.lookup_0": [], - "seed.generated_0.lookup_1": [], - "model.generated_0.configured_label": [], - "model.generated_0.is_placed": [], - "model.generated_0.table_fn__events_above": [ - "model.generated_0.stg_sales_1" - ], - "model.generated_0.tidy_status": [], - "model.generated_0.is_large": [] - }, - "group_map": {}, - "docs": {}, - "saved_queries": {}, - "semantic_models": {}, - "unit_tests": {} - } + "compiled": {}, + "manifest": null } diff --git a/tests/goldens/compiler/seed/10.json b/tests/goldens/compiler/seed/10.json index 2dbbb539c3..a6a3bdf907 100644 --- a/tests/goldens/compiler/seed/10.json +++ b/tests/goldens/compiler/seed/10.json @@ -37,7 +37,7 @@ "stdout": { "target": { "resource_type": "model", - "resource_name": "cte_facts_stg_sales_0", + "resource_name": "cte_facts_stg_inventory_1", "column_name": "amount" }, "direction": "upstream", @@ -51,12 +51,12 @@ { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "cte_facts_stg_sales_0", + "resource_name": "cte_facts_stg_inventory_1", "column_name": "amount" }, "transform": "direct", @@ -65,12 +65,12 @@ { "source": { "resource_type": "source", - "resource_name": "raw_events_1", + "resource_name": "raw_events_0", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "transform": "direct", @@ -86,26 +86,26 @@ "stdout": { "target": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "direction": "downstream", "metadata": { "mode": "rich", "max_depth": null, - "analyzed_models": 7, + "analyzed_models": 6, "truncated": false }, "trace": [ { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "cte_facts_stg_sales_0", + "resource_name": "cte_facts_stg_inventory_1", "column_name": "amount" }, "transform": "direct", @@ -114,12 +114,12 @@ { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "merge_stg_sales_0", + "resource_name": "guarded_stg_inventory_1", "column_name": "amount" }, "transform": "direct", @@ -128,27 +128,27 @@ { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "spaced_stg_sales_0", - "column_name": "amount" + "resource_name": "taxed_stg_inventory_1", + "column_name": "taxed" }, - "transform": "direct", + "transform": "expression", "confidence": "high" }, { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "taxed_stg_sales_0", - "column_name": "taxed" + "resource_name": "taxed_stg_inventory_1", + "column_name": "rounded" }, "transform": "expression", "confidence": "high" @@ -156,13 +156,27 @@ { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "taxed_stg_sales_0", - "column_name": "rounded" + "resource_name": "inventory_summary_0", + "column_name": "amount" + }, + "transform": "direct", + "confidence": "high" + }, + { + "source": { + "resource_type": "model", + "resource_name": "stg_inventory_1", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "inventory_summary_0", + "column_name": "adjust_1_amount" }, "transform": "expression", "confidence": "high" @@ -170,12 +184,12 @@ { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "sales_summary_0", + "resource_name": "inventory_summary_1", "column_name": "amount" }, "transform": "direct", @@ -191,7 +205,7 @@ "stdout": { "target": { "resource_type": "model", - "resource_name": "cte_facts_stg_sales_0", + "resource_name": "cte_facts_stg_inventory_1", "column_name": "amount" }, "direction": "upstream", @@ -205,12 +219,12 @@ { "source": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "cte_facts_stg_sales_0", + "resource_name": "cte_facts_stg_inventory_1", "column_name": "amount" }, "transform": "cast", @@ -219,12 +233,12 @@ { "source": { "resource_type": "source", - "resource_name": "raw_events_1", + "resource_name": "raw_events_0", "column_name": "amount" }, "target": { "resource_type": "model", - "resource_name": "stg_sales_0", + "resource_name": "stg_inventory_1", "column_name": "amount" }, "transform": "direct", @@ -240,170 +254,171 @@ "stdout": { "nodes": [ { - "id": "model:copied_stg_sales_0", - "name": "copied_stg_sales_0", + "id": "model:cte_facts_stg_inventory_1", + "name": "cte_facts_stg_inventory_1", "resource_type": "model", - "relative_path": "models/features/copied_stg_sales_0.sql", - "qualified_name": "main.copied_stg_sales_0" + "relative_path": "models/analysis/cte_facts_stg_inventory_1.sql", + "qualified_name": "analytics.cte_facts_stg_inventory_1" }, { - "id": "model:cte_facts_stg_sales_0", - "name": "cte_facts_stg_sales_0", + "id": "model:guarded_stg_inventory_1", + "name": "guarded_stg_inventory_1", "resource_type": "model", - "relative_path": "models/analysis/cte_facts_stg_sales_0.sql", - "qualified_name": "main.cte_facts_stg_sales_0" + "relative_path": "models/features/guarded_stg_inventory_1.sql", + "qualified_name": "analytics.guarded_stg_inventory_1" }, { - "id": "model:merge_stg_sales_0", - "name": "merge_stg_sales_0", + "id": "model:inventory_summary_0", + "name": "inventory_summary_0", "resource_type": "model", - "relative_path": "models/features/merge_stg_sales_0.sql", - "qualified_name": "main.merge_stg_sales_0" + "relative_path": "models/inventory/marts/inventory_summary_0.sql", + "qualified_name": "analytics.inventory_summary_0" }, { - "id": "model:sales_summary_0", - "name": "sales_summary_0", + "id": "model:inventory_summary_1", + "name": "inventory_summary_1", "resource_type": "model", - "relative_path": "models/sales/marts/sales_summary_0.sql", - "qualified_name": "main.sales_summary_0" + "relative_path": "models/inventory/marts/inventory_summary_1.sql", + "qualified_name": "analytics.inventory_summary_1" }, { - "id": "model:spaced_stg_sales_0", - "name": "spaced_stg_sales_0", + "id": "model:stg_inventory_1", + "name": "stg_inventory_1", "resource_type": "model", - "relative_path": "models/features/spaced_stg_sales_0.sql", - "qualified_name": "main.spaced_stg_sales_0" + "relative_path": "models/inventory/staging/stg_inventory_1.sql", + "qualified_name": "analytics.stg_inventory_1" }, { - "id": "model:stg_sales_0", - "name": "stg_sales_0", + "id": "model:taxed_stg_inventory_1", + "name": "taxed_stg_inventory_1", "resource_type": "model", - "relative_path": "models/sales/staging/stg_sales_0.sql", - "qualified_name": "main.stg_sales_0" + "relative_path": "models/features/taxed_stg_inventory_1.sql", + "qualified_name": "analytics.taxed_stg_inventory_1" }, { - "id": "model:taxed_stg_sales_0", - "name": "taxed_stg_sales_0", - "resource_type": "model", - "relative_path": "models/features/taxed_stg_sales_0.sql", - "qualified_name": "main.taxed_stg_sales_0" - }, - { - "id": "source:raw_events_1", - "name": "raw_events_1", + "id": "source:raw_events_0", + "name": "raw_events_0", "resource_type": "source", "relative_path": "sources/raw.yml" } ], "edges": [ { - "from": "model:stg_sales_0", - "to": "model:copied_stg_sales_0" - }, - { - "from": "model:stg_sales_0", - "to": "model:cte_facts_stg_sales_0" + "from": "model:stg_inventory_1", + "to": "model:cte_facts_stg_inventory_1" }, { - "from": "model:stg_sales_0", - "to": "model:merge_stg_sales_0" + "from": "model:stg_inventory_1", + "to": "model:guarded_stg_inventory_1" }, { - "from": "model:stg_sales_0", - "to": "model:sales_summary_0" + "from": "model:stg_inventory_1", + "to": "model:inventory_summary_0" }, { - "from": "model:stg_sales_0", - "to": "model:spaced_stg_sales_0" + "from": "model:stg_inventory_1", + "to": "model:inventory_summary_1" }, { - "from": "source:raw_events_1", - "to": "model:stg_sales_0" + "from": "source:raw_events_0", + "to": "model:stg_inventory_1" }, { - "from": "model:stg_sales_0", - "to": "model:taxed_stg_sales_0" + "from": "model:stg_inventory_1", + "to": "model:taxed_stg_inventory_1" } ], "focus": [ - "model:stg_sales_0" + "model:stg_inventory_1" ], "direction": "both" } } ], "compiled": { - "audits/generic/audited_stg_fulfillment_1/id_present__id.sql": [ + "audits/generic/audited_stg_sales_0/id_present__id.sql": [ "SELECT id", - "FROM __ref(\"audited_stg_fulfillment_1\")", + "FROM __ref(\"audited_stg_sales_0\")", "WHERE id IS NULL", "" ], - "audits/generic/checked_stg_fulfillment_0/accepted_values__status.sql": [ + "audits/generic/checked_stg_sales_0/accepted_values__status.sql": [ "SELECT status", - "FROM __ref(\"checked_stg_fulfillment_0\")", + "FROM __ref(\"checked_stg_sales_0\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/checked_stg_fulfillment_0/expression_is_true.sql": [ + "audits/generic/checked_stg_sales_0/expression_is_true.sql": [ "SELECT *", - "FROM __ref(\"checked_stg_fulfillment_0\")", + "FROM __ref(\"checked_stg_sales_0\")", "WHERE NOT (amount >= -1000)", "" ], - "audits/generic/checked_stg_fulfillment_0/relationships__id.sql": [ + "audits/generic/checked_stg_sales_0/relationships__id.sql": [ "SELECT id", - "FROM __ref(\"checked_stg_fulfillment_0\")", + "FROM __ref(\"checked_stg_sales_0\")", "WHERE id IS NOT NULL", " AND id NOT IN (", " SELECT id", - " FROM __ref(\"stg_fulfillment_0\")", + " FROM __ref(\"stg_sales_0\")", " WHERE id IS NOT NULL", " )", "" ], - "audits/generic/fulfillment_summary_1/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"fulfillment_summary_1\")", - "WHERE id IS NULL", - "" - ], "audits/generic/guarded_stg_inventory_1/amount_at_least__amount.sql": [ "SELECT *", "FROM __ref(\"guarded_stg_inventory_1\")", "WHERE amount < 0", "" ], - "audits/generic/stated_stg_fulfillment_1/accepted_values__status.sql": [ + "audits/generic/inventory_summary_0/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"inventory_summary_0\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/sales_summary_0/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"sales_summary_0\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/stated_stg_sales_0/accepted_values__status.sql": [ "SELECT status", - "FROM __ref(\"stated_stg_fulfillment_1\")", + "FROM __ref(\"stated_stg_sales_0\")", "WHERE status IS NOT NULL", " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], + "audits/generic/stg_fulfillment_0/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"stg_fulfillment_0\")", + "WHERE id IS NULL", + "" + ], "audits/generic/stg_fulfillment_1/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_1\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_inventory_1/not_null__id.sql": [ + "audits/generic/stg_inventory_0/not_null__id.sql": [ "SELECT id", - "FROM __ref(\"stg_inventory_1\")", + "FROM __ref(\"stg_inventory_0\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_sales_0/not_null__id.sql": [ + "audits/generic/stg_inventory_1/not_null__id.sql": [ "SELECT id", - "FROM __ref(\"stg_sales_0\")", + "FROM __ref(\"stg_inventory_1\")", "WHERE id IS NULL", "" ], - "audits/singular/fulfillment_summary_1_matches.sql": [ + "audits/singular/inventory_summary_0_matches.sql": [ "SELECT a.id", - "FROM __ref(\"fulfillment_summary_1\") a", - "LEFT JOIN __ref(\"fulfillment_summary_0\") b ON a.id = b.id", + "FROM __ref(\"inventory_summary_0\") a", + "LEFT JOIN __ref(\"inventory_summary_1\") b ON a.id = b.id", "WHERE b.id IS NULL", "" ], @@ -412,68 +427,68 @@ "" ], "functions/sql/is_placed.sql": [ - "CREATE OR REPLACE MACRO main.is_placed(event_status) AS (", + "CREATE OR REPLACE MACRO analytics.is_placed(event_status) AS (", "event_status = 'placed'", ")", "" ], "functions/sql/table_fn__events_above.sql": [ - "CREATE OR REPLACE MACRO main.table_fn__events_above(p_minimum) AS TABLE", + "CREATE OR REPLACE MACRO analytics.table_fn__events_above(p_minimum) AS TABLE", "SELECT id, amount", - "FROM __ref(\"stg_inventory_0\")", + "FROM __ref(\"stg_fulfillment_1\")", "WHERE amount > p_minimum", "" ], - "models/analysis/chain_1_stg_sales_0.sql": [ + "models/analysis/chain_1_stg_inventory_0.sql": [ "SELECT id, label, amount", - "FROM __ref(\"contracted_stg_sales_0\")", + "FROM __ref(\"contracted_stg_inventory_0\")", "" ], - "models/analysis/chain_2_stg_sales_0.sql": [ + "models/analysis/chain_2_stg_inventory_0.sql": [ "SELECT id, UPPER(label) AS label, amount", - "FROM __ref(\"chain_1_stg_sales_0\")", + "FROM __ref(\"chain_1_stg_inventory_0\")", "" ], - "models/analysis/chain_3_stg_sales_0.sql": [ + "models/analysis/chain_3_stg_inventory_0.sql": [ "SELECT id, label, amount", - "FROM __ref(\"chain_2_stg_sales_0\")", + "FROM __ref(\"chain_2_stg_inventory_0\")", "" ], - "models/analysis/checked_stg_fulfillment_0.sql": [ + "models/analysis/checked_stg_sales_0.sql": [ "SELECT id, amount, status", - "FROM __ref(\"stg_fulfillment_0\")", + "FROM __ref(\"stg_sales_0\")", "" ], - "models/analysis/contracted_stg_sales_0.sql": [ - "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(34)) AS label,", + "models/analysis/contracted_stg_inventory_0.sql": [ + "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(22)) AS label,", " amount", - "FROM __source(\"raw_events_1\")", + "FROM __source(\"raw_events_0\")", "" ], - "models/analysis/cte_facts_stg_sales_0.sql": [ + "models/analysis/cte_facts_stg_inventory_1.sql": [ "WITH base AS (", " SELECT id, CAST(amount AS DECIMAL(12, 2)) AS amount, 'event' AS kind,", " COALESCE(status, 'unknown') AS status", - " FROM __ref(\"stg_sales_0\")", + " FROM __ref(\"stg_inventory_1\")", " WHERE id IS NOT NULL", ")", "SELECT id + 0 AS id, amount, UPPER(kind) AS kind, UPPER(status) AS status", "FROM base", "" ], - "models/analysis/regional_stg_inventory_0.sql": [ - "SELECT id, amount, 'north' AS region", - "FROM __ref(\"stg_inventory_0\")", + "models/analysis/regional_stg_fulfillment_1.sql": [ + "SELECT id, amount, 'south' AS region", + "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/features/audited_stg_fulfillment_1.sql": [ + "models/features/audited_stg_sales_0.sql": [ "SELECT id, amount", - "FROM __ref(\"stg_fulfillment_1\")", + "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/check_history_stg_fulfillment_1.sql": [ + "models/features/check_history_stg_inventory_0.sql": [ "SELECT id, status, amount", - "FROM __ref(\"stg_fulfillment_1\")", + "FROM __ref(\"stg_inventory_0\")", "" ], "models/features/copied_stg_sales_0.sql": [ @@ -481,10 +496,10 @@ "FROM __ref(\"stg_sales_0\")", "" ], - "models/features/flagged_stg_inventory_1.sql": [ + "models/features/flagged_stg_sales_0.sql": [ "SELECT id, __udf(\"is_placed\")(status) AS is_placed,", " __udf(\"is_large\")(amount) AS is_large", - "FROM __ref(\"stg_inventory_1\")", + "FROM __ref(\"stg_sales_0\")", "" ], "models/features/guarded_stg_inventory_1.sql": [ @@ -492,9 +507,9 @@ "FROM __ref(\"stg_inventory_1\")", "" ], - "models/features/merge_stg_sales_0.sql": [ + "models/features/merge_stg_fulfillment_1.sql": [ "SELECT id, amount, status, created_at", - "FROM __ref(\"stg_sales_0\")", + "FROM __ref(\"stg_fulfillment_1\")", "" ], "models/features/product_labels.sql": [ @@ -502,18 +517,18 @@ "FROM __source(\"loaded_products\")", "" ], - "models/features/spaced_stg_sales_0.sql": [ - "-- Généré pour 東京 warehouse", + "models/features/spaced_stg_fulfillment_1.sql": [ + "-- Généré pour naïve résumé", "SELECT", "\tid,", - "\t'naïve résumé' AS label, -- étiquette ✓", + "\t'東京 warehouse' AS label, -- étiquette ✓", "\tamount", - "FROM __ref(\"stg_sales_0\")", + "FROM __ref(\"stg_fulfillment_1\")", "" ], - "models/features/taxed_stg_sales_0.sql": [ + "models/features/taxed_stg_inventory_1.sql": [ "SELECT id, ROUND(amount * 1.2, 2) AS taxed, ROUND(amount, 1) AS rounded", - "FROM __ref(\"stg_sales_0\")", + "FROM __ref(\"stg_inventory_1\")", "" ], "models/fulfillment/marts/fulfillment_summary_0.sql": [ @@ -522,7 +537,8 @@ " t.amount,", " t.status,", " t.created_at,", - " (t.amount * (1 - 12345.678)) AS adjust_0_amount", + " (t.amount * (1 - 0.1)) AS adjust_0_amount,", + " 'naïve résumé' AS site_label", "FROM __ref(\"stg_fulfillment_1\") t", "" ], @@ -541,8 +557,9 @@ " t.amount,", " t.status,", " t.created_at,", - " (t.amount * (1 - 12345.678)) AS adjust_0_amount,", - " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount", + " (t.amount * (1 - 0.1)) AS adjust_0_amount,", + " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount,", + " 'naïve résumé' AS site_label", "FROM __source(\"raw_events_2\") t", "" ], @@ -553,7 +570,7 @@ " t.status,", " t.created_at,", " 3 AS priority,", - " (t.amount * (1 - 12345.678)) AS adjust_0_amount,", + " (t.amount * (1 - 0.1)) AS adjust_0_amount,", " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount", "FROM __source(\"raw_events_0\") t", "" @@ -574,7 +591,8 @@ " t.id,", " t.amount,", " t.status,", - " t.created_at", + " t.created_at,", + " 'naïve résumé' AS site_label", "FROM __ref(\"stg_inventory_1\") t", "" ], @@ -584,7 +602,8 @@ " t.amount,", " t.status,", " t.created_at,", - " (t.amount + 2 + 1) AS adjust_2_amount", + " (t.amount + 2 + 1) AS adjust_2_amount,", + " 'naïve résumé' AS site_label", "FROM __source(\"raw_events_0\") t", "" ], @@ -593,8 +612,7 @@ " t.id,", " t.amount,", " t.status,", - " t.created_at,", - " 'naïve résumé' AS site_label", + " t.created_at", "FROM __source(\"raw_events_0\") t", "" ], @@ -603,21 +621,21 @@ "FROM __table_fn(\"table_fn__events_above\")(1.5)", "" ], - "models/rendering/latest_raw_events_2.sql": [ + "models/rendering/latest_raw_events_0.sql": [ "SELECT id, amount", - "FROM (SELECT id, amount FROM __source(\"raw_events_2\") ORDER BY id DESC LIMIT 2) AS latest", + "FROM (SELECT id, amount FROM __source(\"raw_events_0\") ORDER BY id DESC LIMIT 2) AS latest", "" ], - "models/rendering/stated_stg_fulfillment_1.sql": [ + "models/rendering/stated_stg_sales_0.sql": [ "SELECT CAST(id AS INTEGER) AS id, status,", - " CASE WHEN amount >= 3 THEN 'HIGH'", + " CASE WHEN amount >= 4 THEN 'HIGH'", " ELSE 'LOW' END AS tier", - "FROM __ref(\"stg_fulfillment_1\")", + "FROM __ref(\"stg_sales_0\")", "" ], "models/rendering/unioned_event_ids.sql": [ "SELECT id", - "FROM (SELECT id FROM __ref(\"stg_fulfillment_0\") UNION ALL SELECT id FROM __ref(\"stg_fulfillment_1\")) AS unioned", + "FROM (SELECT id FROM __ref(\"stg_fulfillment_1\") UNION ALL SELECT id FROM __ref(\"stg_inventory_0\")) AS unioned", "" ], "models/sales/marts/sales_summary_0.sql": [ @@ -626,8 +644,7 @@ " t.amount,", " t.status,", " t.created_at,", - " 3 AS priority,", - " 'naïve résumé' AS site_label", + " 3 AS priority", "FROM __ref(\"stg_sales_0\") t", "WHERE t.status <> 'returned ✓'", "" @@ -650,35 +667,33 @@ "SELECT 0 AS step_index, 'macro taxes_amounts' AS model_name, (SELECT COUNT(*) FROM __actual__macro_taxes_amounts) AS actual_count, (SELECT COUNT(*) FROM __expected__macro_taxes_amounts) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__macro_taxes_amounts EXCEPT SELECT * FROM __expected__macro_taxes_amounts) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__macro_taxes_amounts EXCEPT SELECT * FROM __actual__macro_taxes_amounts) AS __sqlbuild_missing) AS missing_count", "" ], - "tests/regional_stg_inventory_0/test_regional_stg_inventory_0.sql": [ - "WITH __ref__stg_inventory_0 AS (SELECT 1 AS id, CAST(4 AS DOUBLE) AS amount, 'placed' AS status,", + "tests/regional_stg_fulfillment_1/test_regional_stg_fulfillment_1.sql": [ + "WITH __ref__stg_fulfillment_1 AS (SELECT 1 AS id, CAST(4 AS DOUBLE) AS amount, 'placed' AS status,", " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__regional_stg_inventory_0 AS (SELECT id, amount, 'west' AS region", - "FROM __ref__stg_inventory_0),", - "__actual__regional_stg_inventory_0 AS (SELECT * FROM __ref__regional_stg_inventory_0),", - "__expected__regional_stg_inventory_0 AS (SELECT 1 AS id, CAST(4 AS DOUBLE) AS amount, 'west' AS region)", - "SELECT 0 AS step_index, 'regional_stg_inventory_0' AS model_name, (SELECT COUNT(*) FROM __actual__regional_stg_inventory_0) AS actual_count, (SELECT COUNT(*) FROM __expected__regional_stg_inventory_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, amount, region FROM __actual__regional_stg_inventory_0 EXCEPT SELECT id, amount, region FROM __expected__regional_stg_inventory_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, amount, region FROM __expected__regional_stg_inventory_0 EXCEPT SELECT id, amount, region FROM __actual__regional_stg_inventory_0) AS __sqlbuild_missing) AS missing_count", + "__ref__regional_stg_fulfillment_1 AS (SELECT id, amount, 'west' AS region", + "FROM __ref__stg_fulfillment_1),", + "__actual__regional_stg_fulfillment_1 AS (SELECT * FROM __ref__regional_stg_fulfillment_1),", + "__expected__regional_stg_fulfillment_1 AS (SELECT 1 AS id, CAST(4 AS DOUBLE) AS amount, 'west' AS region)", + "SELECT 0 AS step_index, 'regional_stg_fulfillment_1' AS model_name, (SELECT COUNT(*) FROM __actual__regional_stg_fulfillment_1) AS actual_count, (SELECT COUNT(*) FROM __expected__regional_stg_fulfillment_1) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, amount, region FROM __actual__regional_stg_fulfillment_1 EXCEPT SELECT id, amount, region FROM __expected__regional_stg_fulfillment_1) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, amount, region FROM __expected__regional_stg_fulfillment_1 EXCEPT SELECT id, amount, region FROM __actual__regional_stg_fulfillment_1) AS __sqlbuild_missing) AS missing_count", "" ], - "tests/stg_fulfillment_0/test_stg_fulfillment_0.sql": [ - "WITH __source__raw_events_2 AS (SELECT 1 AS id, CAST(10 AS DOUBLE) AS amount, 'placed' AS status,", + "tests/stg_inventory_1/test_stg_inventory_1.sql": [ + "WITH __source__raw_events_0 AS (SELECT 1 AS id, CAST(10 AS DOUBLE) AS amount, 'placed' AS status,", " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__stg_fulfillment_0 AS (SELECT", + "__ref__stg_inventory_1 AS (SELECT", " t.id,", " t.amount,", " t.status,", - " t.created_at,", - " (t.amount * (1 - 12345.678)) AS adjust_0_amount,", - " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount", - "FROM __source__raw_events_2 t),", - "__actual__stg_fulfillment_0 AS (SELECT * FROM __ref__stg_fulfillment_0),", - "__expected__stg_fulfillment_0 AS (SELECT 1 AS id, 'placed' AS status)", - "SELECT 0 AS step_index, 'stg_fulfillment_0' AS model_name, (SELECT COUNT(*) FROM __actual__stg_fulfillment_0) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_fulfillment_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __actual__stg_fulfillment_0 EXCEPT SELECT id, status FROM __expected__stg_fulfillment_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __expected__stg_fulfillment_0 EXCEPT SELECT id, status FROM __actual__stg_fulfillment_0) AS __sqlbuild_missing) AS missing_count", + " t.created_at", + "FROM __source__raw_events_0 t),", + "__actual__stg_inventory_1 AS (SELECT * FROM __ref__stg_inventory_1),", + "__expected__stg_inventory_1 AS (SELECT 1 AS id, 'placed' AS status)", + "SELECT 0 AS step_index, 'stg_inventory_1' AS model_name, (SELECT COUNT(*) FROM __actual__stg_inventory_1) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_inventory_1) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __actual__stg_inventory_1 EXCEPT SELECT id, status FROM __expected__stg_inventory_1) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __expected__stg_inventory_1 EXCEPT SELECT id, status FROM __actual__stg_inventory_1) AS __sqlbuild_missing) AS missing_count", "" ], "tests/udf detects_placed_events/detects_placed_events.sql": [ "WITH input_values AS (SELECT 'placed' AS event_status),", - "__actual__udf_detects_placed_events AS (SELECT event_status, main.is_placed(event_status) AS is_placed", + "__actual__udf_detects_placed_events AS (SELECT event_status, analytics.is_placed(event_status) AS is_placed", " FROM input_values),", "__expected__udf_detects_placed_events AS (SELECT 'placed' AS event_status, TRUE AS is_placed)", "SELECT 0 AS step_index, 'udf detects_placed_events' AS model_name, (SELECT COUNT(*) FROM __actual__udf_detects_placed_events) AS actual_count, (SELECT COUNT(*) FROM __expected__udf_detects_placed_events) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__udf_detects_placed_events EXCEPT SELECT * FROM __expected__udf_detects_placed_events) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__udf_detects_placed_events EXCEPT SELECT * FROM __actual__udf_detects_placed_events) AS __sqlbuild_missing) AS missing_count", @@ -687,31 +702,31 @@ }, "manifest": { "nodes": { - "model.generated_10.chain_1_stg_sales_0": { + "model.generated_10.chain_1_stg_inventory_0": { "database": null, - "schema": "main", - "name": "chain_1_stg_sales_0", + "schema": "analytics", + "name": "chain_1_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/chain_1_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_1_stg_sales_0.sql", - "unique_id": "model.generated_10.chain_1_stg_sales_0", + "path": "models/analysis/chain_1_stg_inventory_0.sql", + "original_file_path": "models/analysis/chain_1_stg_inventory_0.sql", + "unique_id": "model.generated_10.chain_1_stg_inventory_0", "fqn": [ "generated_10", "models", "analysis", - "chain_1_stg_sales_0" + "chain_1_stg_inventory_0" ], - "alias": "chain_1_stg_sales_0", + "alias": "chain_1_stg_inventory_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -735,7 +750,7 @@ } }, "tags": [], - "description": "Level 1 below the contracted copy of stg_sales_0", + "description": "Level 1 below the contracted copy of stg_inventory_0", "columns": {}, "meta": {}, "group": null, @@ -748,39 +763,39 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.chain_1_stg_sales_0", + "relation_name": "analytics.chain_1_stg_inventory_0", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.contracted_stg_sales_0" + "model.generated_10.contracted_stg_inventory_0" ] } }, - "model.generated_10.chain_2_stg_sales_0": { + "model.generated_10.chain_2_stg_inventory_0": { "database": null, - "schema": "main", - "name": "chain_2_stg_sales_0", + "schema": "analytics", + "name": "chain_2_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/chain_2_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_2_stg_sales_0.sql", - "unique_id": "model.generated_10.chain_2_stg_sales_0", + "path": "models/analysis/chain_2_stg_inventory_0.sql", + "original_file_path": "models/analysis/chain_2_stg_inventory_0.sql", + "unique_id": "model.generated_10.chain_2_stg_inventory_0", "fqn": [ "generated_10", "models", "analysis", - "chain_2_stg_sales_0" + "chain_2_stg_inventory_0" ], - "alias": "chain_2_stg_sales_0", + "alias": "chain_2_stg_inventory_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -804,7 +819,7 @@ } }, "tags": [], - "description": "Level 2 below the contracted copy of stg_sales_0", + "description": "Level 2 below the contracted copy of stg_inventory_0", "columns": {}, "meta": {}, "group": null, @@ -817,39 +832,39 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.chain_2_stg_sales_0", + "relation_name": "analytics.chain_2_stg_inventory_0", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.chain_1_stg_sales_0" + "model.generated_10.chain_1_stg_inventory_0" ] } }, - "model.generated_10.chain_3_stg_sales_0": { + "model.generated_10.chain_3_stg_inventory_0": { "database": null, - "schema": "main", - "name": "chain_3_stg_sales_0", + "schema": "analytics", + "name": "chain_3_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/chain_3_stg_sales_0.sql", - "original_file_path": "models/analysis/chain_3_stg_sales_0.sql", - "unique_id": "model.generated_10.chain_3_stg_sales_0", + "path": "models/analysis/chain_3_stg_inventory_0.sql", + "original_file_path": "models/analysis/chain_3_stg_inventory_0.sql", + "unique_id": "model.generated_10.chain_3_stg_inventory_0", "fqn": [ "generated_10", "models", "analysis", - "chain_3_stg_sales_0" + "chain_3_stg_inventory_0" ], - "alias": "chain_3_stg_sales_0", + "alias": "chain_3_stg_inventory_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -873,7 +888,7 @@ } }, "tags": [], - "description": "Level 3 below the contracted copy of stg_sales_0", + "description": "Level 3 below the contracted copy of stg_inventory_0", "columns": {}, "meta": {}, "group": null, @@ -886,34 +901,34 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.chain_3_stg_sales_0", + "relation_name": "analytics.chain_3_stg_inventory_0", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.chain_2_stg_sales_0" + "model.generated_10.chain_2_stg_inventory_0" ] } }, - "model.generated_10.checked_stg_fulfillment_0": { + "model.generated_10.checked_stg_sales_0": { "database": null, - "schema": "main", - "name": "checked_stg_fulfillment_0", + "schema": "analytics", + "name": "checked_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/checked_stg_fulfillment_0.sql", - "original_file_path": "models/analysis/checked_stg_fulfillment_0.sql", - "unique_id": "model.generated_10.checked_stg_fulfillment_0", + "path": "models/analysis/checked_stg_sales_0.sql", + "original_file_path": "models/analysis/checked_stg_sales_0.sql", + "unique_id": "model.generated_10.checked_stg_sales_0", "fqn": [ "generated_10", "models", "analysis", - "checked_stg_fulfillment_0" + "checked_stg_sales_0" ], - "alias": "checked_stg_fulfillment_0", + "alias": "checked_stg_sales_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, @@ -944,7 +959,7 @@ } }, "tags": [], - "description": "Metadata-checked copy of stg_fulfillment_0", + "description": "Metadata-checked copy of stg_sales_0", "columns": { "id": { "name": "id", @@ -976,34 +991,34 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.checked_stg_fulfillment_0", + "relation_name": "analytics.checked_stg_sales_0", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_fulfillment_0" + "model.generated_10.stg_sales_0" ] } }, - "model.generated_10.contracted_stg_sales_0": { + "model.generated_10.contracted_stg_inventory_0": { "database": null, - "schema": "main", - "name": "contracted_stg_sales_0", + "schema": "analytics", + "name": "contracted_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/contracted_stg_sales_0.sql", - "original_file_path": "models/analysis/contracted_stg_sales_0.sql", - "unique_id": "model.generated_10.contracted_stg_sales_0", + "path": "models/analysis/contracted_stg_inventory_0.sql", + "original_file_path": "models/analysis/contracted_stg_inventory_0.sql", + "unique_id": "model.generated_10.contracted_stg_inventory_0", "fqn": [ "generated_10", "models", "analysis", - "contracted_stg_sales_0" + "contracted_stg_inventory_0" ], - "alias": "contracted_stg_sales_0", + "alias": "contracted_stg_inventory_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, @@ -1032,7 +1047,7 @@ } }, "tags": [], - "description": "Contracted copy of raw_events_1", + "description": "Contracted copy of raw_events_0", "columns": { "id": { "name": "id", @@ -1047,7 +1062,7 @@ "name": "label", "description": "", "meta": {}, - "data_type": "VARCHAR(34)", + "data_type": "VARCHAR(22)", "constraints": [], "quote": null, "tags": [] @@ -1073,39 +1088,39 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.contracted_stg_sales_0", + "relation_name": "analytics.contracted_stg_inventory_0", "depends_on": { "macros": [], "nodes": [ - "source.generated_10.raw_events_1" + "source.generated_10.raw_events_0" ] } }, - "model.generated_10.cte_facts_stg_sales_0": { + "model.generated_10.cte_facts_stg_inventory_1": { "database": null, - "schema": "main", - "name": "cte_facts_stg_sales_0", + "schema": "analytics", + "name": "cte_facts_stg_inventory_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/cte_facts_stg_sales_0.sql", - "original_file_path": "models/analysis/cte_facts_stg_sales_0.sql", - "unique_id": "model.generated_10.cte_facts_stg_sales_0", + "path": "models/analysis/cte_facts_stg_inventory_1.sql", + "original_file_path": "models/analysis/cte_facts_stg_inventory_1.sql", + "unique_id": "model.generated_10.cte_facts_stg_inventory_1", "fqn": [ "generated_10", "models", "analysis", - "cte_facts_stg_sales_0" + "cte_facts_stg_inventory_1" ], - "alias": "cte_facts_stg_sales_0", + "alias": "cte_facts_stg_inventory_1", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1129,7 +1144,7 @@ } }, "tags": [], - "description": "Contracted CTE reads of stg_sales_0", + "description": "Contracted CTE reads of stg_inventory_1", "columns": { "id": { "name": "id", @@ -1179,39 +1194,39 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.cte_facts_stg_sales_0", + "relation_name": "analytics.cte_facts_stg_inventory_1", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_sales_0" + "model.generated_10.stg_inventory_1" ] } }, - "model.generated_10.regional_stg_inventory_0": { + "model.generated_10.regional_stg_fulfillment_1": { "database": null, - "schema": "main", - "name": "regional_stg_inventory_0", + "schema": "analytics", + "name": "regional_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/analysis/regional_stg_inventory_0.sql", - "original_file_path": "models/analysis/regional_stg_inventory_0.sql", - "unique_id": "model.generated_10.regional_stg_inventory_0", + "path": "models/analysis/regional_stg_fulfillment_1.sql", + "original_file_path": "models/analysis/regional_stg_fulfillment_1.sql", + "unique_id": "model.generated_10.regional_stg_fulfillment_1", "fqn": [ "generated_10", "models", "analysis", - "regional_stg_inventory_0" + "regional_stg_fulfillment_1" ], - "alias": "regional_stg_inventory_0", + "alias": "regional_stg_fulfillment_1", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1235,7 +1250,7 @@ } }, "tags": [], - "description": "Regional copy of stg_inventory_0", + "description": "Regional copy of stg_fulfillment_1", "columns": {}, "meta": {}, "group": null, @@ -1248,39 +1263,39 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.regional_stg_inventory_0", + "relation_name": "analytics.regional_stg_fulfillment_1", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_inventory_0" + "model.generated_10.stg_fulfillment_1" ] } }, - "model.generated_10.audited_stg_fulfillment_1": { + "model.generated_10.audited_stg_sales_0": { "database": null, - "schema": "main", - "name": "audited_stg_fulfillment_1", + "schema": "analytics", + "name": "audited_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/audited_stg_fulfillment_1.sql", - "original_file_path": "models/features/audited_stg_fulfillment_1.sql", - "unique_id": "model.generated_10.audited_stg_fulfillment_1", + "path": "models/features/audited_stg_sales_0.sql", + "original_file_path": "models/features/audited_stg_sales_0.sql", + "unique_id": "model.generated_10.audited_stg_sales_0", "fqn": [ "generated_10", "models", "features", - "audited_stg_fulfillment_1" + "audited_stg_sales_0" ], - "alias": "audited_stg_fulfillment_1", + "alias": "audited_stg_sales_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1304,7 +1319,7 @@ } }, "tags": [], - "description": "Factory-audited copy of stg_fulfillment_1", + "description": "Factory-audited copy of stg_sales_0", "columns": {}, "meta": {}, "group": null, @@ -1317,34 +1332,34 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.audited_stg_fulfillment_1", + "relation_name": "analytics.audited_stg_sales_0", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_fulfillment_1" + "model.generated_10.stg_sales_0" ] } }, - "model.generated_10.check_history_stg_fulfillment_1": { + "model.generated_10.check_history_stg_inventory_0": { "database": null, - "schema": "main", - "name": "check_history_stg_fulfillment_1", + "schema": "analytics", + "name": "check_history_stg_inventory_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/check_history_stg_fulfillment_1.sql", - "original_file_path": "models/features/check_history_stg_fulfillment_1.sql", - "unique_id": "model.generated_10.check_history_stg_fulfillment_1", + "path": "models/features/check_history_stg_inventory_0.sql", + "original_file_path": "models/features/check_history_stg_inventory_0.sql", + "unique_id": "model.generated_10.check_history_stg_inventory_0", "fqn": [ "generated_10", "models", "features", - "check_history_stg_fulfillment_1" + "check_history_stg_inventory_0" ], - "alias": "check_history_stg_fulfillment_1", + "alias": "check_history_stg_inventory_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, @@ -1375,7 +1390,7 @@ } }, "tags": [], - "description": "Check history of stg_fulfillment_1", + "description": "Check history of stg_inventory_0", "columns": {}, "meta": {}, "group": null, @@ -1388,17 +1403,17 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.check_history_stg_fulfillment_1", + "relation_name": "analytics.check_history_stg_inventory_0", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_fulfillment_1" + "model.generated_10.stg_inventory_0" ] } }, "model.generated_10.copied_stg_sales_0": { "database": null, - "schema": "main", + "schema": "analytics", "name": "copied_stg_sales_0", "resource_type": "model", "package_name": "generated_10", @@ -1415,7 +1430,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, @@ -1457,7 +1472,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.copied_stg_sales_0", + "relation_name": "analytics.copied_stg_sales_0", "depends_on": { "macros": [], "nodes": [ @@ -1465,31 +1480,31 @@ ] } }, - "model.generated_10.flagged_stg_inventory_1": { + "model.generated_10.flagged_stg_sales_0": { "database": null, - "schema": "main", - "name": "flagged_stg_inventory_1", + "schema": "analytics", + "name": "flagged_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/flagged_stg_inventory_1.sql", - "original_file_path": "models/features/flagged_stg_inventory_1.sql", - "unique_id": "model.generated_10.flagged_stg_inventory_1", + "path": "models/features/flagged_stg_sales_0.sql", + "original_file_path": "models/features/flagged_stg_sales_0.sql", + "unique_id": "model.generated_10.flagged_stg_sales_0", "fqn": [ "generated_10", "models", "features", - "flagged_stg_inventory_1" + "flagged_stg_sales_0" ], - "alias": "flagged_stg_inventory_1", + "alias": "flagged_stg_sales_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1513,7 +1528,7 @@ } }, "tags": [], - "description": "Function-flagged copy of stg_inventory_1", + "description": "Function-flagged copy of stg_sales_0", "columns": {}, "meta": {}, "group": null, @@ -1526,19 +1541,19 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.flagged_stg_inventory_1", + "relation_name": "analytics.flagged_stg_sales_0", "depends_on": { "macros": [], "nodes": [ "model.generated_10.is_placed", "model.generated_10.is_large", - "model.generated_10.stg_inventory_1" + "model.generated_10.stg_sales_0" ] } }, "model.generated_10.guarded_stg_inventory_1": { "database": null, - "schema": "main", + "schema": "analytics", "name": "guarded_stg_inventory_1", "resource_type": "model", "package_name": "generated_10", @@ -1555,12 +1570,12 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1607,7 +1622,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.guarded_stg_inventory_1", + "relation_name": "analytics.guarded_stg_inventory_1", "depends_on": { "macros": [], "nodes": [ @@ -1615,26 +1630,26 @@ ] } }, - "model.generated_10.merge_stg_sales_0": { + "model.generated_10.merge_stg_fulfillment_1": { "database": null, - "schema": "main", - "name": "merge_stg_sales_0", + "schema": "analytics", + "name": "merge_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/merge_stg_sales_0.sql", - "original_file_path": "models/features/merge_stg_sales_0.sql", - "unique_id": "model.generated_10.merge_stg_sales_0", + "path": "models/features/merge_stg_fulfillment_1.sql", + "original_file_path": "models/features/merge_stg_fulfillment_1.sql", + "unique_id": "model.generated_10.merge_stg_fulfillment_1", "fqn": [ "generated_10", "models", "features", - "merge_stg_sales_0" + "merge_stg_fulfillment_1" ], - "alias": "merge_stg_sales_0", + "alias": "merge_stg_fulfillment_1", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, @@ -1665,7 +1680,7 @@ } }, "tags": [], - "description": "Incremental merge copy of stg_sales_0", + "description": "Incremental merge copy of stg_fulfillment_1", "columns": {}, "meta": {}, "group": null, @@ -1678,17 +1693,17 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.merge_stg_sales_0", + "relation_name": "analytics.merge_stg_fulfillment_1", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_sales_0" + "model.generated_10.stg_fulfillment_1" ] } }, "model.generated_10.product_labels": { "database": null, - "schema": "main", + "schema": "analytics", "name": "product_labels", "resource_type": "model", "package_name": "generated_10", @@ -1705,7 +1720,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, @@ -1747,7 +1762,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.product_labels", + "relation_name": "analytics.product_labels", "depends_on": { "macros": [], "nodes": [ @@ -1755,26 +1770,26 @@ ] } }, - "model.generated_10.spaced_stg_sales_0": { + "model.generated_10.spaced_stg_fulfillment_1": { "database": null, - "schema": "main", - "name": "spaced_stg_sales_0", + "schema": "analytics", + "name": "spaced_stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/spaced_stg_sales_0.sql", - "original_file_path": "models/features/spaced_stg_sales_0.sql", - "unique_id": "model.generated_10.spaced_stg_sales_0", + "path": "models/features/spaced_stg_fulfillment_1.sql", + "original_file_path": "models/features/spaced_stg_fulfillment_1.sql", + "unique_id": "model.generated_10.spaced_stg_fulfillment_1", "fqn": [ "generated_10", "models", "features", - "spaced_stg_sales_0" + "spaced_stg_fulfillment_1" ], - "alias": "spaced_stg_sales_0", + "alias": "spaced_stg_fulfillment_1", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "línea", @@ -1782,7 +1797,7 @@ ], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1809,7 +1824,7 @@ "línea", "東京" ], - "description": "Copy of stg_sales_0 with café ☕ counter", + "description": "Copy of stg_fulfillment_1 with 東京 warehouse", "columns": {}, "meta": {}, "group": null, @@ -1822,39 +1837,39 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.spaced_stg_sales_0", + "relation_name": "analytics.spaced_stg_fulfillment_1", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_sales_0" + "model.generated_10.stg_fulfillment_1" ] } }, - "model.generated_10.taxed_stg_sales_0": { + "model.generated_10.taxed_stg_inventory_1": { "database": null, - "schema": "main", - "name": "taxed_stg_sales_0", + "schema": "analytics", + "name": "taxed_stg_inventory_1", "resource_type": "model", "package_name": "generated_10", - "path": "models/features/taxed_stg_sales_0.sql", - "original_file_path": "models/features/taxed_stg_sales_0.sql", - "unique_id": "model.generated_10.taxed_stg_sales_0", + "path": "models/features/taxed_stg_inventory_1.sql", + "original_file_path": "models/features/taxed_stg_inventory_1.sql", + "unique_id": "model.generated_10.taxed_stg_inventory_1", "fqn": [ "generated_10", "models", "features", - "taxed_stg_sales_0" + "taxed_stg_inventory_1" ], - "alias": "taxed_stg_sales_0", + "alias": "taxed_stg_inventory_1", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1878,7 +1893,7 @@ } }, "tags": [], - "description": "Taxed copy of stg_sales_0", + "description": "Taxed copy of stg_inventory_1", "columns": {}, "meta": {}, "group": null, @@ -1891,17 +1906,17 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.taxed_stg_sales_0", + "relation_name": "analytics.taxed_stg_inventory_1", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_sales_0" + "model.generated_10.stg_inventory_1" ] } }, "model.generated_10.fulfillment_summary_0": { "database": null, - "schema": "main", + "schema": "analytics", "name": "fulfillment_summary_0", "resource_type": "model", "package_name": "generated_10", @@ -1919,7 +1934,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "fulfillment", @@ -1927,7 +1942,7 @@ ], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -1967,7 +1982,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.fulfillment_summary_0", + "relation_name": "analytics.fulfillment_summary_0", "depends_on": { "macros": [], "nodes": [ @@ -1977,7 +1992,7 @@ }, "model.generated_10.fulfillment_summary_1": { "database": null, - "schema": "main", + "schema": "analytics", "name": "fulfillment_summary_1", "resource_type": "model", "package_name": "generated_10", @@ -1995,7 +2010,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "fulfillment", @@ -2003,7 +2018,7 @@ ], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -2031,17 +2046,7 @@ "marts" ], "description": "Summary of fulfillment activity 1", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, + "columns": {}, "meta": {}, "group": null, "docs": { @@ -2053,7 +2058,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.fulfillment_summary_1", + "relation_name": "analytics.fulfillment_summary_1", "depends_on": { "macros": [], "nodes": [ @@ -2063,7 +2068,7 @@ }, "model.generated_10.stg_fulfillment_0": { "database": null, - "schema": "main", + "schema": "analytics", "name": "stg_fulfillment_0", "resource_type": "model", "package_name": "generated_10", @@ -2081,7 +2086,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "staging" @@ -2115,7 +2120,17 @@ "staging" ], "description": "Staged fulfillment events 0", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": {}, "group": null, "docs": { @@ -2127,7 +2142,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.stg_fulfillment_0", + "relation_name": "analytics.stg_fulfillment_0", "depends_on": { "macros": [], "nodes": [ @@ -2137,7 +2152,7 @@ }, "model.generated_10.stg_fulfillment_1": { "database": null, - "schema": "main", + "schema": "analytics", "name": "stg_fulfillment_1", "resource_type": "model", "package_name": "generated_10", @@ -2155,7 +2170,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "staging" @@ -2211,7 +2226,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.stg_fulfillment_1", + "relation_name": "analytics.stg_fulfillment_1", "depends_on": { "macros": [], "nodes": [ @@ -2221,7 +2236,7 @@ }, "model.generated_10.inventory_summary_0": { "database": null, - "schema": "main", + "schema": "analytics", "name": "inventory_summary_0", "resource_type": "model", "package_name": "generated_10", @@ -2239,12 +2254,9 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, - "tags": [ - "inventory", - "marts" - ], + "tags": [], "meta": {}, "group": null, "materialized": "view", @@ -2253,12 +2265,12 @@ "persist_docs": {}, "post-hook": [ { - "sql": "SELECT 'main.inventory_summary_0' AS refreshed_relation, 'café ☕ counter' AS refresh_label", + "sql": "SELECT 'analytics.inventory_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", "transaction": true, "index": 0 }, { - "sql": "SELECT 'main.inventory_summary_0' AS refreshed", + "sql": "SELECT 'analytics.inventory_summary_0' AS refreshed", "transaction": true, "index": 1 } @@ -2281,31 +2293,38 @@ "alias_types": true } }, - "tags": [ - "inventory", - "marts" - ], + "tags": [], "description": "Summary of inventory activity 0 (東京 warehouse)", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": { "sqlbuild": { "lifecycle_hooks": { "post_hooks": [ { "type": "sql", - "statement": "SELECT 'main.inventory_summary_0' AS refreshed_relation, 'café ☕ counter' AS refresh_label", + "statement": "SELECT 'analytics.inventory_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", "name": "record_refresh", "relative_path": "hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", - "label": "café ☕ counter" + "label": "naïve résumé" }, "description": "Record a refresh for one relation" }, { "type": "sql", - "statement": "SELECT 'main.inventory_summary_0' AS refreshed" + "statement": "SELECT 'analytics.inventory_summary_0' AS refreshed" } ] } @@ -2321,7 +2340,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.inventory_summary_0", + "relation_name": "analytics.inventory_summary_0", "depends_on": { "macros": [], "nodes": [ @@ -2331,7 +2350,7 @@ }, "model.generated_10.inventory_summary_1": { "database": null, - "schema": "main", + "schema": "analytics", "name": "inventory_summary_1", "resource_type": "model", "package_name": "generated_10", @@ -2349,30 +2368,16 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, - "tags": [ - "inventory", - "marts" - ], + "tags": [], "meta": {}, "group": null, "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'main.inventory_summary_1' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'main.inventory_summary_1' AS refreshed", - "transaction": true, - "index": 1 - } - ], + "post-hook": [], "pre-hook": [], "quoting": {}, "column_types": {}, @@ -2391,36 +2396,10 @@ "alias_types": true } }, - "tags": [ - "inventory", - "marts" - ], + "tags": [], "description": "Summary of inventory activity 1", "columns": {}, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'main.inventory_summary_1' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "Ελληνικά orders" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'main.inventory_summary_1' AS refreshed" - } - ] - } - } - }, + "meta": {}, "group": null, "docs": { "show": true, @@ -2431,7 +2410,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.inventory_summary_1", + "relation_name": "analytics.inventory_summary_1", "depends_on": { "macros": [], "nodes": [ @@ -2441,7 +2420,7 @@ }, "model.generated_10.stg_inventory_0": { "database": null, - "schema": "main", + "schema": "analytics", "name": "stg_inventory_0", "resource_type": "model", "package_name": "generated_10", @@ -2459,7 +2438,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "staging" @@ -2493,7 +2472,17 @@ "staging" ], "description": "Staged inventory events 0 (café ☕ counter)", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": {}, "group": null, "docs": { @@ -2505,7 +2494,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.stg_inventory_0", + "relation_name": "analytics.stg_inventory_0", "depends_on": { "macros": [], "nodes": [ @@ -2515,7 +2504,7 @@ }, "model.generated_10.stg_inventory_1": { "database": null, - "schema": "main", + "schema": "analytics", "name": "stg_inventory_1", "resource_type": "model", "package_name": "generated_10", @@ -2533,7 +2522,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "staging" @@ -2589,7 +2578,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.stg_inventory_1", + "relation_name": "analytics.stg_inventory_1", "depends_on": { "macros": [], "nodes": [ @@ -2599,7 +2588,7 @@ }, "model.generated_10.large_events": { "database": null, - "schema": "main", + "schema": "analytics", "name": "large_events", "resource_type": "model", "package_name": "generated_10", @@ -2616,12 +2605,12 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -2658,7 +2647,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.large_events", + "relation_name": "analytics.large_events", "depends_on": { "macros": [], "nodes": [ @@ -2666,31 +2655,31 @@ ] } }, - "model.generated_10.latest_raw_events_2": { + "model.generated_10.latest_raw_events_0": { "database": null, - "schema": "main", - "name": "latest_raw_events_2", + "schema": "analytics", + "name": "latest_raw_events_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/rendering/latest_raw_events_2.sql", - "original_file_path": "models/rendering/latest_raw_events_2.sql", - "unique_id": "model.generated_10.latest_raw_events_2", + "path": "models/rendering/latest_raw_events_0.sql", + "original_file_path": "models/rendering/latest_raw_events_0.sql", + "unique_id": "model.generated_10.latest_raw_events_0", "fqn": [ "generated_10", "models", "rendering", - "latest_raw_events_2" + "latest_raw_events_0" ], - "alias": "latest_raw_events_2", + "alias": "latest_raw_events_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -2714,7 +2703,7 @@ } }, "tags": [], - "description": "Newest rows of raw_events_2", + "description": "Newest rows of raw_events_0", "columns": {}, "meta": {}, "group": null, @@ -2727,39 +2716,39 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.latest_raw_events_2", + "relation_name": "analytics.latest_raw_events_0", "depends_on": { "macros": [], "nodes": [ - "source.generated_10.raw_events_2" + "source.generated_10.raw_events_0" ] } }, - "model.generated_10.stated_stg_fulfillment_1": { + "model.generated_10.stated_stg_sales_0": { "database": null, - "schema": "main", - "name": "stated_stg_fulfillment_1", + "schema": "analytics", + "name": "stated_stg_sales_0", "resource_type": "model", "package_name": "generated_10", - "path": "models/rendering/stated_stg_fulfillment_1.sql", - "original_file_path": "models/rendering/stated_stg_fulfillment_1.sql", - "unique_id": "model.generated_10.stated_stg_fulfillment_1", + "path": "models/rendering/stated_stg_sales_0.sql", + "original_file_path": "models/rendering/stated_stg_sales_0.sql", + "unique_id": "model.generated_10.stated_stg_sales_0", "fqn": [ "generated_10", "models", "rendering", - "stated_stg_fulfillment_1" + "stated_stg_sales_0" ], - "alias": "stated_stg_fulfillment_1", + "alias": "stated_stg_sales_0", "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -2783,7 +2772,7 @@ } }, "tags": [], - "description": "Enum-typed copy of stg_fulfillment_1", + "description": "Enum-typed copy of stg_sales_0", "columns": { "id": { "name": "id", @@ -2824,17 +2813,17 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.stated_stg_fulfillment_1", + "relation_name": "analytics.stated_stg_sales_0", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_fulfillment_1" + "model.generated_10.stg_sales_0" ] } }, "model.generated_10.unioned_event_ids": { "database": null, - "schema": "main", + "schema": "analytics", "name": "unioned_event_ids", "resource_type": "model", "package_name": "generated_10", @@ -2851,12 +2840,12 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [], "meta": {}, "group": null, - "materialized": "table", + "materialized": "view", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, @@ -2893,18 +2882,18 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.unioned_event_ids", + "relation_name": "analytics.unioned_event_ids", "depends_on": { "macros": [], "nodes": [ - "model.generated_10.stg_fulfillment_0", - "model.generated_10.stg_fulfillment_1" + "model.generated_10.stg_fulfillment_1", + "model.generated_10.stg_inventory_0" ] } }, "model.generated_10.sales_summary_0": { "database": null, - "schema": "main", + "schema": "analytics", "name": "sales_summary_0", "resource_type": "model", "package_name": "generated_10", @@ -2922,7 +2911,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "sales", @@ -2930,18 +2919,18 @@ ], "meta": {}, "group": null, - "materialized": "view", + "materialized": "table", "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, "post-hook": [ { - "sql": "SELECT 'main.sales_summary_0' AS refreshed_relation, 'Zürich – depot' AS refresh_label", + "sql": "SELECT 'analytics.sales_summary_0' AS refreshed_relation, 'Zürich – depot' AS refresh_label", "transaction": true, "index": 0 }, { - "sql": "SELECT 'main.sales_summary_0' AS refreshed", + "sql": "SELECT 'analytics.sales_summary_0' AS refreshed", "transaction": true, "index": 1 } @@ -2969,14 +2958,24 @@ "marts" ], "description": "Summary of sales activity 0", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": { "sqlbuild": { "lifecycle_hooks": { "post_hooks": [ { "type": "sql", - "statement": "SELECT 'main.sales_summary_0' AS refreshed_relation, 'Zürich – depot' AS refresh_label", + "statement": "SELECT 'analytics.sales_summary_0' AS refreshed_relation, 'Zürich – depot' AS refresh_label", "name": "record_refresh", "relative_path": "hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", @@ -2988,7 +2987,7 @@ }, { "type": "sql", - "statement": "SELECT 'main.sales_summary_0' AS refreshed" + "statement": "SELECT 'analytics.sales_summary_0' AS refreshed" } ] } @@ -3004,7 +3003,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.sales_summary_0", + "relation_name": "analytics.sales_summary_0", "depends_on": { "macros": [], "nodes": [ @@ -3014,7 +3013,7 @@ }, "model.generated_10.stg_sales_0": { "database": null, - "schema": "main", + "schema": "analytics", "name": "stg_sales_0", "resource_type": "model", "package_name": "generated_10", @@ -3032,7 +3031,7 @@ "config": { "enabled": true, "alias": null, - "schema": "main", + "schema": "analytics", "database": null, "tags": [ "staging" @@ -3066,17 +3065,7 @@ "staging" ], "description": "Staged sales events 0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, + "columns": {}, "meta": {}, "group": null, "docs": { @@ -3088,7 +3077,7 @@ "unrendered_config": {}, "config_call_dict": {}, "unrendered_config_call_dict": {}, - "relation_name": "main.stg_sales_0", + "relation_name": "analytics.stg_sales_0", "depends_on": { "macros": [], "nodes": [ @@ -3100,7 +3089,7 @@ "sources": { "source.generated_10.loaded_products": { "database": null, - "schema": "main", + "schema": "analytics", "name": "loaded_products", "resource_type": "source", "package_name": "generated_10", @@ -3467,7 +3456,7 @@ "path": "models/analysis/_sqlbuild/_macros/python/regions.py", "original_file_path": "models/analysis/_sqlbuild/_macros/python/regions.py", "unique_id": "macro.generated_10.analysis_region", - "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'north'\"\n", + "macro_sql": "def analysis_region() -> str:\n \"\"\"Return the region rows are assigned to.\"\"\"\n return \"'south'\"\n", "depends_on": { "macros": [] }, @@ -3611,55 +3600,55 @@ "selectors": {}, "disabled": {}, "parent_map": { - "model.generated_10.chain_1_stg_sales_0": [ - "model.generated_10.contracted_stg_sales_0" - ], - "model.generated_10.chain_2_stg_sales_0": [ - "model.generated_10.chain_1_stg_sales_0" + "model.generated_10.chain_1_stg_inventory_0": [ + "model.generated_10.contracted_stg_inventory_0" ], - "model.generated_10.chain_3_stg_sales_0": [ - "model.generated_10.chain_2_stg_sales_0" + "model.generated_10.chain_2_stg_inventory_0": [ + "model.generated_10.chain_1_stg_inventory_0" ], - "model.generated_10.checked_stg_fulfillment_0": [ - "model.generated_10.stg_fulfillment_0" - ], - "model.generated_10.contracted_stg_sales_0": [ - "source.generated_10.raw_events_1" + "model.generated_10.chain_3_stg_inventory_0": [ + "model.generated_10.chain_2_stg_inventory_0" ], - "model.generated_10.cte_facts_stg_sales_0": [ + "model.generated_10.checked_stg_sales_0": [ "model.generated_10.stg_sales_0" ], - "model.generated_10.regional_stg_inventory_0": [ - "model.generated_10.stg_inventory_0" + "model.generated_10.contracted_stg_inventory_0": [ + "source.generated_10.raw_events_0" ], - "model.generated_10.audited_stg_fulfillment_1": [ - "model.generated_10.stg_fulfillment_1" + "model.generated_10.cte_facts_stg_inventory_1": [ + "model.generated_10.stg_inventory_1" ], - "model.generated_10.check_history_stg_fulfillment_1": [ + "model.generated_10.regional_stg_fulfillment_1": [ "model.generated_10.stg_fulfillment_1" ], + "model.generated_10.audited_stg_sales_0": [ + "model.generated_10.stg_sales_0" + ], + "model.generated_10.check_history_stg_inventory_0": [ + "model.generated_10.stg_inventory_0" + ], "model.generated_10.copied_stg_sales_0": [ "model.generated_10.stg_sales_0" ], - "model.generated_10.flagged_stg_inventory_1": [ + "model.generated_10.flagged_stg_sales_0": [ "model.generated_10.is_placed", "model.generated_10.is_large", - "model.generated_10.stg_inventory_1" + "model.generated_10.stg_sales_0" ], "model.generated_10.guarded_stg_inventory_1": [ "model.generated_10.stg_inventory_1" ], - "model.generated_10.merge_stg_sales_0": [ - "model.generated_10.stg_sales_0" + "model.generated_10.merge_stg_fulfillment_1": [ + "model.generated_10.stg_fulfillment_1" ], "model.generated_10.product_labels": [ "source.generated_10.loaded_products" ], - "model.generated_10.spaced_stg_sales_0": [ - "model.generated_10.stg_sales_0" + "model.generated_10.spaced_stg_fulfillment_1": [ + "model.generated_10.stg_fulfillment_1" ], - "model.generated_10.taxed_stg_sales_0": [ - "model.generated_10.stg_sales_0" + "model.generated_10.taxed_stg_inventory_1": [ + "model.generated_10.stg_inventory_1" ], "model.generated_10.fulfillment_summary_0": [ "model.generated_10.stg_fulfillment_1" @@ -3688,15 +3677,15 @@ "model.generated_10.large_events": [ "model.generated_10.table_fn__events_above" ], - "model.generated_10.latest_raw_events_2": [ - "source.generated_10.raw_events_2" + "model.generated_10.latest_raw_events_0": [ + "source.generated_10.raw_events_0" ], - "model.generated_10.stated_stg_fulfillment_1": [ - "model.generated_10.stg_fulfillment_1" + "model.generated_10.stated_stg_sales_0": [ + "model.generated_10.stg_sales_0" ], "model.generated_10.unioned_event_ids": [ - "model.generated_10.stg_fulfillment_0", - "model.generated_10.stg_fulfillment_1" + "model.generated_10.stg_fulfillment_1", + "model.generated_10.stg_inventory_0" ], "model.generated_10.sales_summary_0": [ "model.generated_10.stg_sales_0" @@ -3710,7 +3699,7 @@ "source.generated_10.raw_events_2": [], "model.generated_10.is_placed": [], "model.generated_10.table_fn__events_above": [ - "model.generated_10.stg_inventory_0" + "model.generated_10.stg_fulfillment_1" ], "model.generated_10.is_large": [] }, diff --git a/tests/goldens/compiler/seed/2.json b/tests/goldens/compiler/seed/2.json index 1bd8afb7da..a3ae59d335 100644 --- a/tests/goldens/compiler/seed/2.json +++ b/tests/goldens/compiler/seed/2.json @@ -2,163 +2,3566 @@ "commands": [ { "label": "compile", - "exit_code": 1, - "diagnostics": [ - { - "phase": "compile", - "severity": "error", - "code": "P001", - "message": "Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'" - } - ] + "exit_code": 0, + "diagnostics": [] }, { "label": "compile-store-warm", - "exit_code": 1, - "diagnostics": [ - { - "phase": "compile", - "severity": "error", - "code": "P001", - "message": "Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'" - } - ] + "exit_code": 0, + "diagnostics": [] }, { "label": "plan", - "exit_code": 1, - "diagnostics": [ - "Project discovery START", - "Project assembly START", - "Declaration parsing START", - "Declaration parsing OK ()", - "Python discovery START", - "Python discovery OK ()", - "Project assembly OK ()", - "Project discovery OK ()", - "Compiling project...", - "error[P001]: Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'", - "", - "" - ] + "exit_code": 0, + "diagnostics": [] }, { "label": "compile-select", - "exit_code": 1, - "diagnostics": [ - { - "phase": "compile", - "severity": "error", - "code": "P001", - "message": "Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'" - } - ] + "exit_code": 0, + "diagnostics": [] }, { "label": "compile-no-analysis", - "exit_code": 1, - "diagnostics": [ - { - "phase": "compile", - "severity": "error", - "code": "P001", - "message": "Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'" - } - ] + "exit_code": 0, + "diagnostics": [] }, { "label": "compile-rich-lineage", - "exit_code": 1, - "diagnostics": [ - { - "phase": "compile", - "severity": "error", - "code": "P001", - "message": "Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'" - } - ] + "exit_code": 0, + "diagnostics": [] }, { "label": "lineage-rich-upstream", - "exit_code": 1, - "diagnostics": [ - "Project discovery START", - "Project assembly START", - "Declaration parsing START", - "Declaration parsing OK ()", - "Python discovery START", - "Python discovery OK ()", - "Project assembly OK ()", - "Project discovery OK ()", - "error[P001]: Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'", - "", - "" - ], - "stdout": [ - "" - ] + "exit_code": 0, + "diagnostics": [], + "stdout": { + "target": { + "resource_type": "model", + "resource_name": "cte_facts_stg_sales_2", + "column_name": "amount" + }, + "direction": "upstream", + "metadata": { + "mode": "rich", + "max_depth": null, + "analyzed_models": 2, + "truncated": false + }, + "trace": [ + { + "source": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "cte_facts_stg_sales_2", + "column_name": "amount" + }, + "transform": "direct", + "confidence": "high" + }, + { + "source": { + "resource_type": "source", + "resource_name": "raw_events_0", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "transform": "direct", + "confidence": "high" + } + ] + } }, { "label": "lineage-rich-downstream", - "exit_code": 1, - "diagnostics": [ - "Project discovery START", - "Project assembly START", - "Declaration parsing START", - "Declaration parsing OK ()", - "Python discovery START", - "Python discovery OK ()", - "Project assembly OK ()", - "Project discovery OK ()", - "error[P001]: Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'", - "", - "" - ], - "stdout": [ - "" - ] + "exit_code": 0, + "diagnostics": [], + "stdout": { + "target": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "direction": "downstream", + "metadata": { + "mode": "rich", + "max_depth": null, + "analyzed_models": 9, + "truncated": false + }, + "trace": [ + { + "source": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "checked_stg_sales_2", + "column_name": "amount" + }, + "transform": "direct", + "confidence": "high" + }, + { + "source": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "cte_facts_stg_sales_2", + "column_name": "amount" + }, + "transform": "direct", + "confidence": "high" + }, + { + "source": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "every_stg_sales_2", + "column_name": "amount" + }, + "transform": "star", + "confidence": "medium" + }, + { + "source": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "typed_stg_sales_2", + "column_name": "doubled_amount" + }, + "transform": "expression", + "confidence": "high" + }, + { + "source": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "check_history_stg_sales_2", + "column_name": "amount" + }, + "transform": "direct", + "confidence": "high" + } + ] + } }, { "label": "lineage-fast-upstream", - "exit_code": 1, - "diagnostics": [ - "Project discovery START", - "Project assembly START", - "Declaration parsing START", - "Declaration parsing OK ()", - "Python discovery START", - "Python discovery OK ()", - "Project assembly OK ()", - "Project discovery OK ()", - "error[P001]: Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'", - "", - "" - ], - "stdout": [ - "" - ] + "exit_code": 0, + "diagnostics": [], + "stdout": { + "target": { + "resource_type": "model", + "resource_name": "cte_facts_stg_sales_2", + "column_name": "amount" + }, + "direction": "upstream", + "metadata": { + "mode": "fast", + "max_depth": null, + "analyzed_models": 2, + "truncated": false + }, + "trace": [ + { + "source": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "cte_facts_stg_sales_2", + "column_name": "amount" + }, + "transform": "cast", + "confidence": "high" + }, + { + "source": { + "resource_type": "source", + "resource_name": "raw_events_0", + "column_name": "amount" + }, + "target": { + "resource_type": "model", + "resource_name": "stg_sales_2", + "column_name": "amount" + }, + "transform": "direct", + "confidence": "high" + } + ] + } }, { "label": "lineage-relations", - "exit_code": 1, - "diagnostics": [ - "Project discovery START", - "Project assembly START", - "Declaration parsing START", - "Declaration parsing OK ()", - "Python discovery START", - "Python discovery OK ()", - "Project assembly OK ()", - "Project discovery OK ()", - "error[P001]: Model file models/sales/marts/sales_summary_1.sql references unknown model 'missing_model'", - "", - "" - ], - "stdout": [ - "" - ] + "exit_code": 0, + "diagnostics": [], + "stdout": { + "nodes": [ + { + "id": "model:check_history_stg_sales_2", + "name": "check_history_stg_sales_2", + "resource_type": "model", + "relative_path": "models/features/check_history_stg_sales_2.sql", + "qualified_name": "analytics.check_history_stg_sales_2" + }, + { + "id": "model:checked_stg_sales_2", + "name": "checked_stg_sales_2", + "resource_type": "model", + "relative_path": "models/analysis/checked_stg_sales_2.sql", + "qualified_name": "analytics.checked_stg_sales_2" + }, + { + "id": "model:combined_stg_sales_2", + "name": "combined_stg_sales_2", + "resource_type": "model", + "relative_path": "models/analysis/combined_stg_sales_2.sql", + "qualified_name": "analytics.combined_stg_sales_2" + }, + { + "id": "model:cte_facts_stg_sales_2", + "name": "cte_facts_stg_sales_2", + "resource_type": "model", + "relative_path": "models/analysis/cte_facts_stg_sales_2.sql", + "qualified_name": "analytics.cte_facts_stg_sales_2" + }, + { + "id": "model:every_stg_sales_2", + "name": "every_stg_sales_2", + "resource_type": "model", + "relative_path": "models/analysis/every_stg_sales_2.sql", + "qualified_name": "analytics.every_stg_sales_2" + }, + { + "id": "model:passed_stg_sales_2", + "name": "passed_stg_sales_2", + "resource_type": "model", + "relative_path": "models/analysis/passed_stg_sales_2.sql", + "qualified_name": "analytics.passed_stg_sales_2" + }, + { + "id": "model:sales_summary_1", + "name": "sales_summary_1", + "resource_type": "model", + "relative_path": "models/sales/marts/sales_summary_1.sql", + "qualified_name": "analytics.sales_summary_1" + }, + { + "id": "model:stg_sales_2", + "name": "stg_sales_2", + "resource_type": "model", + "relative_path": "models/sales/staging/stg_sales_2.sql", + "qualified_name": "analytics.stg_sales_2" + }, + { + "id": "model:typed_stg_sales_2", + "name": "typed_stg_sales_2", + "resource_type": "model", + "relative_path": "models/analysis/typed_stg_sales_2.sql", + "qualified_name": "analytics.typed_stg_sales_2" + }, + { + "id": "source:raw_events_0", + "name": "raw_events_0", + "resource_type": "source", + "relative_path": "sources/raw.yml" + } + ], + "edges": [ + { + "from": "model:stg_sales_2", + "to": "model:check_history_stg_sales_2" + }, + { + "from": "model:stg_sales_2", + "to": "model:checked_stg_sales_2" + }, + { + "from": "model:stg_sales_2", + "to": "model:combined_stg_sales_2" + }, + { + "from": "model:stg_sales_2", + "to": "model:cte_facts_stg_sales_2" + }, + { + "from": "model:stg_sales_2", + "to": "model:every_stg_sales_2" + }, + { + "from": "model:stg_sales_2", + "to": "model:passed_stg_sales_2" + }, + { + "from": "model:stg_sales_2", + "to": "model:sales_summary_1" + }, + { + "from": "source:raw_events_0", + "to": "model:stg_sales_2" + }, + { + "from": "model:stg_sales_2", + "to": "model:typed_stg_sales_2" + } + ], + "focus": [ + "model:stg_sales_2" + ], + "direction": "both" + } } ], - "compiled": {}, - "manifest": null + "compiled": { + "audits/generic/audited_stg_sales_0/id_present__id.sql": [ + "SELECT id", + "FROM __ref(\"audited_stg_sales_0\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/checked_stg_sales_2/accepted_values__status.sql": [ + "SELECT status", + "FROM __ref(\"checked_stg_sales_2\")", + "WHERE status IS NOT NULL", + " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", + "" + ], + "audits/generic/checked_stg_sales_2/expression_is_true.sql": [ + "SELECT *", + "FROM __ref(\"checked_stg_sales_2\")", + "WHERE NOT (amount >= -1000)", + "" + ], + "audits/generic/checked_stg_sales_2/relationships__id.sql": [ + "SELECT id", + "FROM __ref(\"checked_stg_sales_2\")", + "WHERE id IS NOT NULL", + " AND id NOT IN (", + " SELECT id", + " FROM __ref(\"stg_sales_2\")", + " WHERE id IS NOT NULL", + " )", + "" + ], + "audits/generic/sales_summary_0/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"sales_summary_0\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/sales_summary_1/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"sales_summary_1\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/stated_stg_sales_1/accepted_values__status.sql": [ + "SELECT status", + "FROM __ref(\"stated_stg_sales_1\")", + "WHERE status IS NOT NULL", + " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", + "" + ], + "audits/generic/stg_sales_1/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"stg_sales_1\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/stg_sales_2/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"stg_sales_2\")", + "WHERE id IS NULL", + "" + ], + "functions/python/is_large.sql": [ + "REGISTER PYTHON FUNCTION is_large(DOUBLE) RETURNS BOOLEAN", + "" + ], + "functions/sql/is_placed.sql": [ + "CREATE OR REPLACE MACRO analytics.is_placed(event_status) AS (", + "event_status = 'placed'", + ")", + "" + ], + "functions/sql/table_fn__events_above.sql": [ + "CREATE OR REPLACE MACRO analytics.table_fn__events_above(p_minimum) AS TABLE", + "SELECT id, amount", + "FROM __ref(\"stg_sales_1\")", + "WHERE amount > p_minimum", + "" + ], + "models/analysis/chain_1_stg_sales_1.sql": [ + "SELECT id, label, amount", + "FROM __ref(\"contracted_stg_sales_1\")", + "" + ], + "models/analysis/chain_2_stg_sales_1.sql": [ + "SELECT id, UPPER(label) AS label, amount", + "FROM __ref(\"chain_1_stg_sales_1\")", + "" + ], + "models/analysis/chain_3_stg_sales_1.sql": [ + "SELECT id, label, amount", + "FROM __ref(\"chain_2_stg_sales_1\")", + "" + ], + "models/analysis/checked_stg_sales_2.sql": [ + "SELECT id, amount, status", + "FROM __ref(\"stg_sales_2\")", + "" + ], + "models/analysis/combined_stg_sales_2.sql": [ + "WITH recent AS (", + " SELECT id, created_at FROM __ref(\"stg_sales_2\") WHERE amount > 0", + "),", + "older AS (", + " SELECT id, created_at FROM __ref(\"stg_sales_2\")", + ")", + "SELECT id, created_at FROM recent", + "UNION ALL", + "SELECT id, created_at FROM older", + "" + ], + "models/analysis/contracted_stg_sales_1.sql": [ + "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR(40)) AS label,", + " amount", + "FROM __source(\"raw_events_0\")", + "" + ], + "models/analysis/cte_facts_stg_sales_2.sql": [ + "WITH base AS (", + " SELECT id, CAST(amount AS DECIMAL(12, 2)) AS amount, 'event' AS kind,", + " COALESCE(status, 'unknown') AS status", + " FROM __ref(\"stg_sales_2\")", + " WHERE id IS NOT NULL", + ")", + "SELECT id + 0 AS id, amount, UPPER(kind) AS kind, UPPER(status) AS status", + "FROM base", + "" + ], + "models/analysis/every_open_event.sql": [ + "SELECT *", + "FROM __source(\"open_events\")", + "" + ], + "models/analysis/every_raw_events_0.sql": [ + "SELECT *", + "FROM __source(\"raw_events_0\")", + "" + ], + "models/analysis/every_stg_sales_2.sql": [ + "SELECT *", + "FROM __ref(\"stg_sales_2\")", + "" + ], + "models/analysis/passed_stg_sales_2.sql": [ + "WITH passthrough AS (", + " SELECT id, created_at FROM __ref(\"stg_sales_2\")", + ")", + "SELECT id, created_at", + "FROM passthrough", + "" + ], + "models/analysis/pivot_input_stg_sales_1.sql": [ + "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR) AS status, amount", + "FROM __ref(\"stg_sales_1\")", + "" + ], + "models/analysis/pivoted_stg_sales_1.sql": [ + "PIVOT __ref(\"pivot_input_stg_sales_1\")", + "ON status", + "USING MAX(amount)", + "GROUP BY id", + "" + ], + "models/analysis/typed_stg_sales_2.sql": [ + "SELECT id, amount * 2 AS doubled_amount, CAST(status AS VARCHAR) AS status_text,", + " created_at, NULL AS missing_note", + "FROM __ref(\"stg_sales_2\")", + "" + ], + "models/features/audited_stg_sales_0.sql": [ + "SELECT id, amount", + "FROM __ref(\"stg_sales_0\")", + "" + ], + "models/features/check_history_stg_sales_2.sql": [ + "SELECT id, status, amount", + "FROM __ref(\"stg_sales_2\")", + "" + ], + "models/features/copied_stg_sales_0.sql": [ + "SELECT id, status", + "FROM __ref(\"stg_sales_0\")", + "" + ], + "models/features/flagged_stg_sales_0.sql": [ + "SELECT id, __udf(\"is_placed\")(status) AS is_placed,", + " __udf(\"is_large\")(amount) AS is_large", + "FROM __ref(\"stg_sales_0\")", + "" + ], + "models/features/merge_stg_sales_1.sql": [ + "SELECT id, amount, status, created_at", + "FROM __ref(\"stg_sales_1\")", + "" + ], + "models/features/spaced_stg_sales_1.sql": [ + "-- Généré pour Zürich – depot", + "SELECT", + "\tid,", + "\t'café ☕ counter' AS label, -- étiquette ✓", + "\tamount", + "FROM __ref(\"stg_sales_1\")", + "" + ], + "models/features/taxed_stg_sales_0.sql": [ + "SELECT id, ROUND(amount * 1.2, 2) AS taxed, ROUND(amount, 1) AS rounded", + "FROM __ref(\"stg_sales_0\")", + "" + ], + "models/rendering/bounded_stg_sales_0.sql": [ + "SELECT id, amount, created_at", + "FROM __ref(\"stg_sales_0\")", + "WHERE created_at >= __cursor_start()", + " AND created_at < __cursor_end()", + "" + ], + "models/rendering/large_events.sql": [ + "SELECT id, amount", + "FROM __table_fn(\"table_fn__events_above\")(4)", + "" + ], + "models/rendering/stated_stg_sales_1.sql": [ + "SELECT CAST(id AS INTEGER) AS id, status,", + " CASE WHEN amount >= 8 THEN 'HIGH'", + " ELSE 'LOW' END AS tier", + "FROM __ref(\"stg_sales_1\")", + "" + ], + "models/sales/marts/sales_summary_0.sql": [ + "SELECT", + " t.id,", + " t.amount,", + " t.status,", + " t.created_at,", + " t.amount * 0.1 AS threshold_1_amount,", + " (t.amount + LENGTH('east')) AS adjust_0_amount,", + " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount,", + " '東京 warehouse' AS site_label", + "FROM __ref(\"stg_sales_1\") t", + "" + ], + "models/sales/marts/sales_summary_1.sql": [ + "SELECT", + " t.id,", + " t.amount,", + " t.status,", + " t.created_at,", + " 3 AS priority,", + " t.amount + 371 AS threshold_0_amount,", + " j2.label AS lookup_label_2,", + " '東京 warehouse' AS site_label", + "FROM __ref(\"stg_sales_1\") t", + "LEFT JOIN __ref(\"stg_sales_2\") j1 ON t.id = j1.id", + "LEFT JOIN __seed(\"lookup_0\") j2 ON t.id = j2.id", + "" + ], + "models/sales/marts/sales_summary_2.sql": [ + "SELECT", + " t.id,", + " t.amount,", + " t.status,", + " t.created_at,", + " t.amount + 371 AS threshold_0_amount,", + " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount,", + " j1.label AS lookup_label_1,", + " '東京 warehouse' AS site_label", + "FROM __ref(\"stg_sales_1\") t", + "LEFT JOIN __seed(\"lookup_0\") j1 ON t.id = j1.id", + "" + ], + "models/sales/staging/stg_sales_0.sql": [ + "SELECT", + " t.id,", + " t.amount,", + " t.status,", + " t.created_at,", + " '東京 warehouse' AS site_label", + "FROM __source(\"raw_events_0\") t", + "" + ], + "models/sales/staging/stg_sales_1.sql": [ + "SELECT", + " t.id,", + " t.amount,", + " t.status,", + " t.created_at,", + " 3 AS priority", + "FROM __source(\"raw_events_0\") t", + "WHERE t.status <> 'placed'", + "" + ], + "models/sales/staging/stg_sales_2.sql": [ + "SELECT", + " t.id,", + " t.amount,", + " t.status,", + " t.created_at,", + " 3 AS priority,", + " t.amount + 371 AS threshold_0_amount,", + " (t.amount + LENGTH('east')) AS adjust_0_amount,", + " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount", + "FROM __source(\"raw_events_0\") t", + "" + ], + "tests/macro taxes_amounts/taxes_amounts.sql": [ + "WITH input_values AS (SELECT 10 AS amount),", + "__actual__macro_taxes_amounts AS (SELECT ROUND(amount * 1.2, 2) AS taxed", + " FROM input_values),", + "__expected__macro_taxes_amounts AS (SELECT 12.0 AS taxed)", + "SELECT 0 AS step_index, 'macro taxes_amounts' AS model_name, (SELECT COUNT(*) FROM __actual__macro_taxes_amounts) AS actual_count, (SELECT COUNT(*) FROM __expected__macro_taxes_amounts) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__macro_taxes_amounts EXCEPT SELECT * FROM __expected__macro_taxes_amounts) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__macro_taxes_amounts EXCEPT SELECT * FROM __actual__macro_taxes_amounts) AS __sqlbuild_missing) AS missing_count", + "" + ], + "tests/stg_sales_2/test_stg_sales_2.sql": [ + "WITH __source__raw_events_0 AS (SELECT 1 AS id, CAST(10 AS DOUBLE) AS amount, 'placed' AS status,", + " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", + "__ref__stg_sales_2 AS (SELECT", + " t.id,", + " t.amount,", + " t.status,", + " t.created_at,", + " 3 AS priority,", + " t.amount + 371 AS threshold_0_amount,", + " (t.amount + LENGTH('east')) AS adjust_0_amount,", + " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_1_amount", + "FROM __source__raw_events_0 t),", + "__actual__stg_sales_2 AS (SELECT * FROM __ref__stg_sales_2),", + "__expected__stg_sales_2 AS (SELECT 1 AS id, 'placed' AS status)", + "SELECT 0 AS step_index, 'stg_sales_2' AS model_name, (SELECT COUNT(*) FROM __actual__stg_sales_2) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_sales_2) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __actual__stg_sales_2 EXCEPT SELECT id, status FROM __expected__stg_sales_2) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __expected__stg_sales_2 EXCEPT SELECT id, status FROM __actual__stg_sales_2) AS __sqlbuild_missing) AS missing_count", + "" + ], + "tests/udf detects_placed_events/detects_placed_events.sql": [ + "WITH input_values AS (SELECT 'placed' AS event_status),", + "__actual__udf_detects_placed_events AS (SELECT event_status, analytics.is_placed(event_status) AS is_placed", + " FROM input_values),", + "__expected__udf_detects_placed_events AS (SELECT 'placed' AS event_status, TRUE AS is_placed)", + "SELECT 0 AS step_index, 'udf detects_placed_events' AS model_name, (SELECT COUNT(*) FROM __actual__udf_detects_placed_events) AS actual_count, (SELECT COUNT(*) FROM __expected__udf_detects_placed_events) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__udf_detects_placed_events EXCEPT SELECT * FROM __expected__udf_detects_placed_events) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__udf_detects_placed_events EXCEPT SELECT * FROM __actual__udf_detects_placed_events) AS __sqlbuild_missing) AS missing_count", + "" + ] + }, + "manifest": { + "nodes": { + "model.generated_2.chain_1_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "chain_1_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/chain_1_stg_sales_1.sql", + "original_file_path": "models/analysis/chain_1_stg_sales_1.sql", + "unique_id": "model.generated_2.chain_1_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "analysis", + "chain_1_stg_sales_1" + ], + "alias": "chain_1_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Level 1 below the contracted copy of stg_sales_1", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.chain_1_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.contracted_stg_sales_1" + ] + } + }, + "model.generated_2.chain_2_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "chain_2_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/chain_2_stg_sales_1.sql", + "original_file_path": "models/analysis/chain_2_stg_sales_1.sql", + "unique_id": "model.generated_2.chain_2_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "analysis", + "chain_2_stg_sales_1" + ], + "alias": "chain_2_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Level 2 below the contracted copy of stg_sales_1", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.chain_2_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.chain_1_stg_sales_1" + ] + } + }, + "model.generated_2.chain_3_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "chain_3_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/chain_3_stg_sales_1.sql", + "original_file_path": "models/analysis/chain_3_stg_sales_1.sql", + "unique_id": "model.generated_2.chain_3_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "analysis", + "chain_3_stg_sales_1" + ], + "alias": "chain_3_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Level 3 below the contracted copy of stg_sales_1", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.chain_3_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.chain_2_stg_sales_1" + ] + } + }, + "model.generated_2.checked_stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "checked_stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/checked_stg_sales_2.sql", + "original_file_path": "models/analysis/checked_stg_sales_2.sql", + "unique_id": "model.generated_2.checked_stg_sales_2", + "fqn": [ + "generated_2", + "models", + "analysis", + "checked_stg_sales_2" + ], + "alias": "checked_stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": [ + "id" + ], + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Metadata-checked copy of stg_sales_2", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + }, + "status": { + "name": "status", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.checked_stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_2" + ] + } + }, + "model.generated_2.combined_stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "combined_stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/combined_stg_sales_2.sql", + "original_file_path": "models/analysis/combined_stg_sales_2.sql", + "unique_id": "model.generated_2.combined_stg_sales_2", + "fqn": [ + "generated_2", + "models", + "analysis", + "combined_stg_sales_2" + ], + "alias": "combined_stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Recent and older rows of stg_sales_2 and stg_sales_2", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.combined_stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_2" + ] + } + }, + "model.generated_2.contracted_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "contracted_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/contracted_stg_sales_1.sql", + "original_file_path": "models/analysis/contracted_stg_sales_1.sql", + "unique_id": "model.generated_2.contracted_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "analysis", + "contracted_stg_sales_1" + ], + "alias": "contracted_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Contracted copy of raw_events_0", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": "INTEGER", + "constraints": [], + "quote": null, + "tags": [] + }, + "label": { + "name": "label", + "description": "", + "meta": {}, + "data_type": "VARCHAR(40)", + "constraints": [], + "quote": null, + "tags": [] + }, + "amount": { + "name": "amount", + "description": "", + "meta": {}, + "data_type": "DOUBLE", + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.contracted_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "source.generated_2.raw_events_0" + ] + } + }, + "model.generated_2.cte_facts_stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "cte_facts_stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/cte_facts_stg_sales_2.sql", + "original_file_path": "models/analysis/cte_facts_stg_sales_2.sql", + "unique_id": "model.generated_2.cte_facts_stg_sales_2", + "fqn": [ + "generated_2", + "models", + "analysis", + "cte_facts_stg_sales_2" + ], + "alias": "cte_facts_stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Contracted CTE reads of stg_sales_2", + "columns": { + "id": { + "name": "id", + "description": "Recovered id", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + }, + "amount": { + "name": "amount", + "description": "Recovered amount", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + }, + "kind": { + "name": "kind", + "description": "Recovered kind", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + }, + "status": { + "name": "status", + "description": "Recovered status", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.cte_facts_stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_2" + ] + } + }, + "model.generated_2.every_open_event": { + "database": null, + "schema": "analytics", + "name": "every_open_event", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/every_open_event.sql", + "original_file_path": "models/analysis/every_open_event.sql", + "unique_id": "model.generated_2.every_open_event", + "fqn": [ + "generated_2", + "models", + "analysis", + "every_open_event" + ], + "alias": "every_open_event", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Every column of an open source", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.every_open_event", + "depends_on": { + "macros": [], + "nodes": [ + "source.generated_2.open_events" + ] + } + }, + "model.generated_2.every_raw_events_0": { + "database": null, + "schema": "analytics", + "name": "every_raw_events_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/every_raw_events_0.sql", + "original_file_path": "models/analysis/every_raw_events_0.sql", + "unique_id": "model.generated_2.every_raw_events_0", + "fqn": [ + "generated_2", + "models", + "analysis", + "every_raw_events_0" + ], + "alias": "every_raw_events_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Every column of raw_events_0", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.every_raw_events_0", + "depends_on": { + "macros": [], + "nodes": [ + "source.generated_2.raw_events_0" + ] + } + }, + "model.generated_2.every_stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "every_stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/every_stg_sales_2.sql", + "original_file_path": "models/analysis/every_stg_sales_2.sql", + "unique_id": "model.generated_2.every_stg_sales_2", + "fqn": [ + "generated_2", + "models", + "analysis", + "every_stg_sales_2" + ], + "alias": "every_stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Every column of stg_sales_2", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.every_stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_2" + ] + } + }, + "model.generated_2.passed_stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "passed_stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/passed_stg_sales_2.sql", + "original_file_path": "models/analysis/passed_stg_sales_2.sql", + "unique_id": "model.generated_2.passed_stg_sales_2", + "fqn": [ + "generated_2", + "models", + "analysis", + "passed_stg_sales_2" + ], + "alias": "passed_stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Columns of stg_sales_2 passed through a CTE", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.passed_stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_2" + ] + } + }, + "model.generated_2.pivot_input_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "pivot_input_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/pivot_input_stg_sales_1.sql", + "original_file_path": "models/analysis/pivot_input_stg_sales_1.sql", + "unique_id": "model.generated_2.pivot_input_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "analysis", + "pivot_input_stg_sales_1" + ], + "alias": "pivot_input_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Contracted pivot input from stg_sales_1", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": "INTEGER", + "constraints": [], + "quote": null, + "tags": [] + }, + "status": { + "name": "status", + "description": "", + "meta": {}, + "data_type": "VARCHAR", + "constraints": [], + "quote": null, + "tags": [] + }, + "amount": { + "name": "amount", + "description": "", + "meta": {}, + "data_type": "DOUBLE", + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.pivot_input_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_1" + ] + } + }, + "model.generated_2.pivoted_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "pivoted_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/pivoted_stg_sales_1.sql", + "original_file_path": "models/analysis/pivoted_stg_sales_1.sql", + "unique_id": "model.generated_2.pivoted_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "analysis", + "pivoted_stg_sales_1" + ], + "alias": "pivoted_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Amounts of stg_sales_1 pivoted by status", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": "INTEGER", + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": { + "sqlbuild": { + "dynamic_columns": [ + { + "name": "status_amounts", + "pivot_column": "status", + "value_column": "amount", + "aggregate": "MAX", + "type": "DOUBLE", + "name_pattern": null + } + ] + } + }, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.pivoted_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.pivot_input_stg_sales_1" + ] + } + }, + "model.generated_2.typed_stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "typed_stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/analysis/typed_stg_sales_2.sql", + "original_file_path": "models/analysis/typed_stg_sales_2.sql", + "unique_id": "model.generated_2.typed_stg_sales_2", + "fqn": [ + "generated_2", + "models", + "analysis", + "typed_stg_sales_2" + ], + "alias": "typed_stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Typed and untyped outputs of stg_sales_2", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.typed_stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_2" + ] + } + }, + "model.generated_2.audited_stg_sales_0": { + "database": null, + "schema": "analytics", + "name": "audited_stg_sales_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/features/audited_stg_sales_0.sql", + "original_file_path": "models/features/audited_stg_sales_0.sql", + "unique_id": "model.generated_2.audited_stg_sales_0", + "fqn": [ + "generated_2", + "models", + "features", + "audited_stg_sales_0" + ], + "alias": "audited_stg_sales_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Factory-audited copy of stg_sales_0", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.audited_stg_sales_0", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_0" + ] + } + }, + "model.generated_2.check_history_stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "check_history_stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/features/check_history_stg_sales_2.sql", + "original_file_path": "models/features/check_history_stg_sales_2.sql", + "unique_id": "model.generated_2.check_history_stg_sales_2", + "fqn": [ + "generated_2", + "models", + "features", + "check_history_stg_sales_2" + ], + "alias": "check_history_stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "snapshot", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": [ + "id" + ], + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Check history of stg_sales_2", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.check_history_stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_2" + ] + } + }, + "model.generated_2.copied_stg_sales_0": { + "database": null, + "schema": "analytics", + "name": "copied_stg_sales_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/features/copied_stg_sales_0.sql", + "original_file_path": "models/features/copied_stg_sales_0.sql", + "unique_id": "model.generated_2.copied_stg_sales_0", + "fqn": [ + "generated_2", + "models", + "features", + "copied_stg_sales_0" + ], + "alias": "copied_stg_sales_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "copy_table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Custom copy of stg_sales_0", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.copied_stg_sales_0", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_0" + ] + } + }, + "model.generated_2.flagged_stg_sales_0": { + "database": null, + "schema": "analytics", + "name": "flagged_stg_sales_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/features/flagged_stg_sales_0.sql", + "original_file_path": "models/features/flagged_stg_sales_0.sql", + "unique_id": "model.generated_2.flagged_stg_sales_0", + "fqn": [ + "generated_2", + "models", + "features", + "flagged_stg_sales_0" + ], + "alias": "flagged_stg_sales_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Function-flagged copy of stg_sales_0", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.flagged_stg_sales_0", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.is_placed", + "model.generated_2.is_large", + "model.generated_2.stg_sales_0" + ] + } + }, + "model.generated_2.merge_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "merge_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/features/merge_stg_sales_1.sql", + "original_file_path": "models/features/merge_stg_sales_1.sql", + "unique_id": "model.generated_2.merge_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "features", + "merge_stg_sales_1" + ], + "alias": "merge_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "incremental", + "incremental_strategy": "merge", + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": [ + "id" + ], + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Incremental merge copy of stg_sales_1", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.merge_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_1" + ] + } + }, + "model.generated_2.spaced_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "spaced_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/features/spaced_stg_sales_1.sql", + "original_file_path": "models/features/spaced_stg_sales_1.sql", + "unique_id": "model.generated_2.spaced_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "features", + "spaced_stg_sales_1" + ], + "alias": "spaced_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [ + "línea", + "東京" + ], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [ + "línea", + "東京" + ], + "description": "Copy of stg_sales_1 with Ελληνικά orders", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.spaced_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_1" + ] + } + }, + "model.generated_2.taxed_stg_sales_0": { + "database": null, + "schema": "analytics", + "name": "taxed_stg_sales_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/features/taxed_stg_sales_0.sql", + "original_file_path": "models/features/taxed_stg_sales_0.sql", + "unique_id": "model.generated_2.taxed_stg_sales_0", + "fqn": [ + "generated_2", + "models", + "features", + "taxed_stg_sales_0" + ], + "alias": "taxed_stg_sales_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Taxed copy of stg_sales_0", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.taxed_stg_sales_0", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_0" + ] + } + }, + "model.generated_2.bounded_stg_sales_0": { + "database": null, + "schema": "analytics", + "name": "bounded_stg_sales_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/rendering/bounded_stg_sales_0.sql", + "original_file_path": "models/rendering/bounded_stg_sales_0.sql", + "unique_id": "model.generated_2.bounded_stg_sales_0", + "fqn": [ + "generated_2", + "models", + "rendering", + "bounded_stg_sales_0" + ], + "alias": "bounded_stg_sales_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "incremental", + "incremental_strategy": "delete_insert", + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": [ + "id" + ], + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Cursor-bounded copy of stg_sales_0", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.bounded_stg_sales_0", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_0" + ] + } + }, + "model.generated_2.large_events": { + "database": null, + "schema": "analytics", + "name": "large_events", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/rendering/large_events.sql", + "original_file_path": "models/rendering/large_events.sql", + "unique_id": "model.generated_2.large_events", + "fqn": [ + "generated_2", + "models", + "rendering", + "large_events" + ], + "alias": "large_events", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Events above a threshold from a table function", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.large_events", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.table_fn__events_above" + ] + } + }, + "model.generated_2.stated_stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "stated_stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/rendering/stated_stg_sales_1.sql", + "original_file_path": "models/rendering/stated_stg_sales_1.sql", + "unique_id": "model.generated_2.stated_stg_sales_1", + "fqn": [ + "generated_2", + "models", + "rendering", + "stated_stg_sales_1" + ], + "alias": "stated_stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [], + "description": "Enum-typed copy of stg_sales_1", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": "INTEGER", + "constraints": [], + "quote": null, + "tags": [] + }, + "status": { + "name": "status", + "description": "", + "meta": {}, + "data_type": "VARCHAR", + "constraints": [], + "quote": null, + "tags": [] + }, + "tier": { + "name": "tier", + "description": "", + "meta": {}, + "data_type": "VARCHAR", + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.stated_stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_1" + ] + } + }, + "model.generated_2.sales_summary_0": { + "database": null, + "schema": "analytics", + "name": "sales_summary_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/sales/marts/sales_summary_0.sql", + "original_file_path": "models/sales/marts/sales_summary_0.sql", + "unique_id": "model.generated_2.sales_summary_0", + "fqn": [ + "generated_2", + "models", + "sales", + "marts", + "sales_summary_0" + ], + "alias": "sales_summary_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [ + "sales", + "marts" + ], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [ + { + "sql": "SELECT 'analytics.sales_summary_0' AS refreshed_relation, '東京 warehouse' AS refresh_label", + "transaction": true, + "index": 0 + }, + { + "sql": "SELECT 'analytics.sales_summary_0' AS refreshed", + "transaction": true, + "index": 1 + } + ], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [ + "sales", + "marts" + ], + "description": "Summary of sales activity 0", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": { + "sqlbuild": { + "lifecycle_hooks": { + "post_hooks": [ + { + "type": "sql", + "statement": "SELECT 'analytics.sales_summary_0' AS refreshed_relation, '東京 warehouse' AS refresh_label", + "name": "record_refresh", + "relative_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", + "kwargs": { + "relation": "@@CTX:destination.qualified", + "label": "東京 warehouse" + }, + "description": "Record a refresh for one relation" + }, + { + "type": "sql", + "statement": "SELECT 'analytics.sales_summary_0' AS refreshed" + } + ] + } + } + }, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.sales_summary_0", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_1" + ] + } + }, + "model.generated_2.sales_summary_1": { + "database": null, + "schema": "analytics", + "name": "sales_summary_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/sales/marts/sales_summary_1.sql", + "original_file_path": "models/sales/marts/sales_summary_1.sql", + "unique_id": "model.generated_2.sales_summary_1", + "fqn": [ + "generated_2", + "models", + "sales", + "marts", + "sales_summary_1" + ], + "alias": "sales_summary_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [ + "sales", + "marts" + ], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [ + { + "sql": "SELECT 'analytics.sales_summary_1' AS refreshed_relation, 'Zürich – depot' AS refresh_label", + "transaction": true, + "index": 0 + }, + { + "sql": "SELECT 'analytics.sales_summary_1' AS refreshed", + "transaction": true, + "index": 1 + } + ], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [ + "sales", + "marts" + ], + "description": "Summary of sales activity 1", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": { + "sqlbuild": { + "lifecycle_hooks": { + "post_hooks": [ + { + "type": "sql", + "statement": "SELECT 'analytics.sales_summary_1' AS refreshed_relation, 'Zürich – depot' AS refresh_label", + "name": "record_refresh", + "relative_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", + "kwargs": { + "relation": "@@CTX:destination.qualified", + "label": "Zürich – depot" + }, + "description": "Record a refresh for one relation" + }, + { + "type": "sql", + "statement": "SELECT 'analytics.sales_summary_1' AS refreshed" + } + ] + } + } + }, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.sales_summary_1", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_1", + "model.generated_2.stg_sales_2", + "seed.generated_2.lookup_0" + ] + } + }, + "model.generated_2.sales_summary_2": { + "database": null, + "schema": "analytics", + "name": "sales_summary_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/sales/marts/sales_summary_2.sql", + "original_file_path": "models/sales/marts/sales_summary_2.sql", + "unique_id": "model.generated_2.sales_summary_2", + "fqn": [ + "generated_2", + "models", + "sales", + "marts", + "sales_summary_2" + ], + "alias": "sales_summary_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [ + "sales", + "marts" + ], + "meta": {}, + "group": null, + "materialized": "table", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [ + { + "sql": "SELECT 'analytics.sales_summary_2' AS refreshed_relation, 'café ☕ counter' AS refresh_label", + "transaction": true, + "index": 0 + }, + { + "sql": "SELECT 'analytics.sales_summary_2' AS refreshed", + "transaction": true, + "index": 1 + } + ], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [ + "sales", + "marts" + ], + "description": "Summary of sales activity 2", + "columns": {}, + "meta": { + "sqlbuild": { + "lifecycle_hooks": { + "post_hooks": [ + { + "type": "sql", + "statement": "SELECT 'analytics.sales_summary_2' AS refreshed_relation, 'café ☕ counter' AS refresh_label", + "name": "record_refresh", + "relative_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", + "kwargs": { + "relation": "@@CTX:destination.qualified", + "label": "café ☕ counter" + }, + "description": "Record a refresh for one relation" + }, + { + "type": "sql", + "statement": "SELECT 'analytics.sales_summary_2' AS refreshed" + } + ] + } + } + }, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.sales_summary_2", + "depends_on": { + "macros": [], + "nodes": [ + "model.generated_2.stg_sales_1", + "seed.generated_2.lookup_0" + ] + } + }, + "model.generated_2.stg_sales_0": { + "database": null, + "schema": "analytics", + "name": "stg_sales_0", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/sales/staging/stg_sales_0.sql", + "original_file_path": "models/sales/staging/stg_sales_0.sql", + "unique_id": "model.generated_2.stg_sales_0", + "fqn": [ + "generated_2", + "models", + "sales", + "staging", + "stg_sales_0" + ], + "alias": "stg_sales_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [ + "staging" + ], + "meta": {}, + "group": null, + "materialized": "view", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [ + "staging" + ], + "description": "Staged sales events 0 (東京 warehouse)", + "columns": {}, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.stg_sales_0", + "depends_on": { + "macros": [], + "nodes": [ + "source.generated_2.raw_events_0" + ] + } + }, + "model.generated_2.stg_sales_1": { + "database": null, + "schema": "analytics", + "name": "stg_sales_1", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/sales/staging/stg_sales_1.sql", + "original_file_path": "models/sales/staging/stg_sales_1.sql", + "unique_id": "model.generated_2.stg_sales_1", + "fqn": [ + "generated_2", + "models", + "sales", + "staging", + "stg_sales_1" + ], + "alias": "stg_sales_1", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [ + "staging" + ], + "meta": {}, + "group": null, + "materialized": "view", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [ + "staging" + ], + "description": "Staged sales events 1", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.stg_sales_1", + "depends_on": { + "macros": [], + "nodes": [ + "source.generated_2.raw_events_0" + ] + } + }, + "model.generated_2.stg_sales_2": { + "database": null, + "schema": "analytics", + "name": "stg_sales_2", + "resource_type": "model", + "package_name": "generated_2", + "path": "models/sales/staging/stg_sales_2.sql", + "original_file_path": "models/sales/staging/stg_sales_2.sql", + "unique_id": "model.generated_2.stg_sales_2", + "fqn": [ + "generated_2", + "models", + "sales", + "staging", + "stg_sales_2" + ], + "alias": "stg_sales_2", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [ + "staging" + ], + "meta": {}, + "group": null, + "materialized": "view", + "incremental_strategy": null, + "merge_exclude_columns": null, + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + } + }, + "tags": [ + "staging" + ], + "description": "Staged sales events 2", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.stg_sales_2", + "depends_on": { + "macros": [], + "nodes": [ + "source.generated_2.raw_events_0" + ] + } + }, + "seed.generated_2.lookup_0": { + "database": null, + "schema": "analytics", + "name": "lookup_0", + "resource_type": "seed", + "package_name": "generated_2", + "path": "seeds/lookup_0.csv", + "original_file_path": "seeds/lookup_0.csv", + "unique_id": "seed.generated_2.lookup_0", + "fqn": [ + "generated_2", + "seeds", + "lookup_0" + ], + "alias": "lookup_0", + "config": { + "enabled": true, + "alias": null, + "schema": "analytics", + "database": null, + "tags": [], + "meta": {}, + "group": null, + "materialized": "seed", + "persist_docs": {}, + "post-hook": [], + "pre-hook": [], + "quoting": {}, + "column_types": {}, + "full_refresh": null, + "unique_key": null, + "on_schema_change": "ignore", + "on_configuration_change": "apply", + "grants": {}, + "packages": [], + "docs": { + "show": true, + "node_color": null + }, + "contract": { + "enforced": false, + "alias_types": true + }, + "delimiter": ",", + "quote_columns": null + }, + "tags": [], + "description": "Generated lookup 0.", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": "INTEGER", + "constraints": [], + "quote": null, + "tags": [] + }, + "label": { + "name": "label", + "description": "", + "meta": {}, + "data_type": "VARCHAR", + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "group": null, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "build_path": null, + "unrendered_config": {}, + "config_call_dict": {}, + "unrendered_config_call_dict": {}, + "relation_name": "analytics.lookup_0", + "root_path": null, + "depends_on": { + "macros": [] + } + } + }, + "sources": { + "source.generated_2.open_events": { + "database": null, + "schema": "", + "name": "open_events", + "resource_type": "source", + "package_name": "generated_2", + "path": "sources/open.yml", + "original_file_path": "sources/open.yml", + "unique_id": "source.generated_2.open_events", + "fqn": [ + "generated_2", + "open_events" + ], + "source_name": "open_events", + "source_description": "", + "loader": "", + "identifier": "open_events", + "quoting": {}, + "loaded_at_field": null, + "freshness": null, + "external": null, + "description": "Events whose columns are only known to the warehouse.", + "columns": {}, + "meta": {}, + "source_meta": {}, + "tags": [], + "config": {}, + "patch_path": null, + "unrendered_config": {}, + "relation_name": null + }, + "source.generated_2.raw_events_0": { + "database": null, + "schema": "", + "name": "raw_events_0", + "resource_type": "source", + "package_name": "generated_2", + "path": "sources/raw.yml", + "original_file_path": "sources/raw.yml", + "unique_id": "source.generated_2.raw_events_0", + "fqn": [ + "generated_2", + "raw_events_0" + ], + "source_name": "raw_events_0", + "source_description": "", + "loader": "", + "identifier": "raw_events_0", + "quoting": {}, + "loaded_at_field": null, + "freshness": null, + "external": null, + "description": "Generated event feed 0.", + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": "INTEGER", + "constraints": [], + "quote": null, + "tags": [] + }, + "amount": { + "name": "amount", + "description": "", + "meta": {}, + "data_type": "DOUBLE", + "constraints": [], + "quote": null, + "tags": [] + }, + "status": { + "name": "status", + "description": "", + "meta": {}, + "data_type": "VARCHAR", + "constraints": [], + "quote": null, + "tags": [] + }, + "created_at": { + "name": "created_at", + "description": "", + "meta": {}, + "data_type": "TIMESTAMP", + "constraints": [], + "quote": null, + "tags": [] + } + }, + "meta": {}, + "source_meta": {}, + "tags": [], + "config": {}, + "patch_path": null, + "unrendered_config": {}, + "relation_name": null + } + }, + "macros": { + "macro.generated_2.round_amount": { + "name": "round_amount", + "resource_type": "macro", + "package_name": "generated_2", + "path": "macros/python/rounding.py", + "original_file_path": "macros/python/rounding.py", + "unique_id": "macro.generated_2.round_amount", + "macro_sql": "def round_amount(expression: str, places: int = 2) -> str:\n \"\"\"Round an amount.\"\"\"\n return f\"ROUND({expression}, {places})\"\n", + "depends_on": { + "macros": [] + }, + "description": "", + "meta": { + "sqlbuild_visibility": "global", + "sqlbuild_scope_path": null + }, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "arguments": [], + "supported_languages": null + }, + "macro.generated_2.taxed": { + "name": "taxed", + "resource_type": "macro", + "package_name": "generated_2", + "path": "macros/python/tax.py", + "original_file_path": "macros/python/tax.py", + "unique_id": "macro.generated_2.taxed", + "macro_sql": "from macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", + "depends_on": { + "macros": [ + "macro.generated_2.round_amount" + ] + }, + "description": "", + "meta": { + "sqlbuild_visibility": "global", + "sqlbuild_scope_path": null + }, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "arguments": [], + "supported_languages": null + }, + "macro.generated_2.adjust_0": { + "name": "adjust_0", + "resource_type": "macro", + "package_name": "generated_2", + "path": "models/sales/_sqlbuild/macros/python/adjust_0.py", + "original_file_path": "models/sales/_sqlbuild/macros/python/adjust_0.py", + "unique_id": "macro.generated_2.adjust_0", + "macro_sql": "import os\n\n\ndef adjust_0(expression: str) -> str:\n \"\"\"Tag an amount with the deployment region.\"\"\"\n region = os.environ.get(\"SQB_DIFFERENTIAL_REGION\", \"east\")\n return f\"({expression} + LENGTH('{region}'))\"\n", + "depends_on": { + "macros": [] + }, + "description": "", + "meta": { + "sqlbuild_visibility": "inherited", + "sqlbuild_scope_path": "models/sales" + }, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "arguments": [], + "supported_languages": null + }, + "macro.generated_2.adjust_1": { + "name": "adjust_1", + "resource_type": "macro", + "package_name": "generated_2", + "path": "models/sales/_sqlbuild/macros/python/adjust_1.py", + "original_file_path": "models/sales/_sqlbuild/macros/python/adjust_1.py", + "unique_id": "macro.generated_2.adjust_1", + "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", + "depends_on": { + "macros": [ + "macro.generated_2.adjust_1_round" + ] + }, + "description": "", + "meta": { + "sqlbuild_visibility": "inherited", + "sqlbuild_scope_path": "models/sales" + }, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "arguments": [], + "supported_languages": null + }, + "macro.generated_2.adjust_1_round": { + "name": "adjust_1_round", + "resource_type": "macro", + "package_name": "generated_2", + "path": "models/sales/_sqlbuild/macros/python/adjust_1.py", + "original_file_path": "models/sales/_sqlbuild/macros/python/adjust_1.py", + "unique_id": "macro.generated_2.adjust_1_round", + "macro_sql": "def adjust_1_round(expression: str) -> str:\n \"\"\"Round an amount to two places.\"\"\"\n return f\"ROUND({expression}, 2)\"\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Double and round an amount.\"\"\"\n return adjust_1_round(f\"({expression} * 2)\")\n", + "depends_on": { + "macros": [] + }, + "description": "", + "meta": { + "sqlbuild_visibility": "inherited", + "sqlbuild_scope_path": "models/sales" + }, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "arguments": [], + "supported_languages": null + }, + "macro.generated_2__sqlbuild_hooks.record_refresh": { + "name": "record_refresh", + "resource_type": "macro", + "package_name": "generated_2__sqlbuild_hooks", + "path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "original_file_path": "models/sales/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "unique_id": "macro.generated_2__sqlbuild_hooks.record_refresh", + "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", + "depends_on": { + "macros": [] + }, + "description": "Record a refresh for one relation", + "meta": { + "sqlbuild_resource_type": "sql_hook", + "sqlbuild_hook_name": "record_refresh" + }, + "docs": { + "show": true, + "node_color": null + }, + "patch_path": null, + "arguments": [], + "supported_languages": null + } + }, + "exposures": {}, + "metrics": {}, + "groups": {}, + "selectors": {}, + "disabled": {}, + "parent_map": { + "model.generated_2.chain_1_stg_sales_1": [ + "model.generated_2.contracted_stg_sales_1" + ], + "model.generated_2.chain_2_stg_sales_1": [ + "model.generated_2.chain_1_stg_sales_1" + ], + "model.generated_2.chain_3_stg_sales_1": [ + "model.generated_2.chain_2_stg_sales_1" + ], + "model.generated_2.checked_stg_sales_2": [ + "model.generated_2.stg_sales_2" + ], + "model.generated_2.combined_stg_sales_2": [ + "model.generated_2.stg_sales_2" + ], + "model.generated_2.contracted_stg_sales_1": [ + "source.generated_2.raw_events_0" + ], + "model.generated_2.cte_facts_stg_sales_2": [ + "model.generated_2.stg_sales_2" + ], + "model.generated_2.every_open_event": [ + "source.generated_2.open_events" + ], + "model.generated_2.every_raw_events_0": [ + "source.generated_2.raw_events_0" + ], + "model.generated_2.every_stg_sales_2": [ + "model.generated_2.stg_sales_2" + ], + "model.generated_2.passed_stg_sales_2": [ + "model.generated_2.stg_sales_2" + ], + "model.generated_2.pivot_input_stg_sales_1": [ + "model.generated_2.stg_sales_1" + ], + "model.generated_2.pivoted_stg_sales_1": [ + "model.generated_2.pivot_input_stg_sales_1" + ], + "model.generated_2.typed_stg_sales_2": [ + "model.generated_2.stg_sales_2" + ], + "model.generated_2.audited_stg_sales_0": [ + "model.generated_2.stg_sales_0" + ], + "model.generated_2.check_history_stg_sales_2": [ + "model.generated_2.stg_sales_2" + ], + "model.generated_2.copied_stg_sales_0": [ + "model.generated_2.stg_sales_0" + ], + "model.generated_2.flagged_stg_sales_0": [ + "model.generated_2.is_placed", + "model.generated_2.is_large", + "model.generated_2.stg_sales_0" + ], + "model.generated_2.merge_stg_sales_1": [ + "model.generated_2.stg_sales_1" + ], + "model.generated_2.spaced_stg_sales_1": [ + "model.generated_2.stg_sales_1" + ], + "model.generated_2.taxed_stg_sales_0": [ + "model.generated_2.stg_sales_0" + ], + "model.generated_2.bounded_stg_sales_0": [ + "model.generated_2.stg_sales_0" + ], + "model.generated_2.large_events": [ + "model.generated_2.table_fn__events_above" + ], + "model.generated_2.stated_stg_sales_1": [ + "model.generated_2.stg_sales_1" + ], + "model.generated_2.sales_summary_0": [ + "model.generated_2.stg_sales_1" + ], + "model.generated_2.sales_summary_1": [ + "model.generated_2.stg_sales_1", + "model.generated_2.stg_sales_2", + "seed.generated_2.lookup_0" + ], + "model.generated_2.sales_summary_2": [ + "model.generated_2.stg_sales_1", + "seed.generated_2.lookup_0" + ], + "model.generated_2.stg_sales_0": [ + "source.generated_2.raw_events_0" + ], + "model.generated_2.stg_sales_1": [ + "source.generated_2.raw_events_0" + ], + "model.generated_2.stg_sales_2": [ + "source.generated_2.raw_events_0" + ], + "source.generated_2.open_events": [], + "source.generated_2.raw_events_0": [], + "seed.generated_2.lookup_0": [], + "model.generated_2.is_placed": [], + "model.generated_2.table_fn__events_above": [ + "model.generated_2.stg_sales_1" + ], + "model.generated_2.is_large": [] + }, + "group_map": {}, + "docs": {}, + "saved_queries": {}, + "semantic_models": {}, + "unit_tests": {} + } } diff --git a/tests/goldens/compiler/seed/3.json b/tests/goldens/compiler/seed/3.json index bf204adb66..bd169a87fa 100644 --- a/tests/goldens/compiler/seed/3.json +++ b/tests/goldens/compiler/seed/3.json @@ -1071,8 +1071,8 @@ "channel": "東京 warehouse" }, "relative_path": "models/features/_sqlbuild/_hooks/python/notify.py", - "definition_hash": "55440ff19f0c4f231ad57d453227a3c9d584b81234ee4b3338a39ccdf59814a8", - "version_hash": "03b4f786f8ab2736e5be2e4de5016bd16ea44d84beca000ec2a53a397e503eb6" + "definition_hash": "4669f6863eaccfebdb6aa5286a58eb944d8b0142ea2bc8e6678cce4efb35bf7e", + "version_hash": "80b0b3a25244f0def68efcbecd29182bfa91d76b9272c4d2147d08ae88260fa2" } ] } diff --git a/tests/goldens/compiler/seed/4.json b/tests/goldens/compiler/seed/4.json index 6680d7699d..e9634c1d1c 100644 --- a/tests/goldens/compiler/seed/4.json +++ b/tests/goldens/compiler/seed/4.json @@ -2000,18 +2000,7 @@ "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'ci_checks.support_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'ci_checks.support_summary_0' AS refreshed", - "transaction": true, - "index": 1 - } - ], + "post-hook": [], "pre-hook": [], "quoting": {}, "column_types": {}, @@ -2046,30 +2035,7 @@ "tags": [] } }, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", - "name": "record_refresh", - "relative_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "naïve résumé" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_0' AS refreshed" - } - ] - } - } - }, + "meta": {}, "group": null, "docs": { "show": true, @@ -3001,30 +2967,6 @@ "patch_path": null, "arguments": [], "supported_languages": null - }, - "macro.generated_4__sqlbuild_hooks.record_refresh": { - "name": "record_refresh", - "resource_type": "macro", - "package_name": "generated_4__sqlbuild_hooks", - "path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "original_file_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "unique_id": "macro.generated_4__sqlbuild_hooks.record_refresh", - "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "depends_on": { - "macros": [] - }, - "description": "Record a refresh for one relation", - "meta": { - "sqlbuild_resource_type": "sql_hook", - "sqlbuild_hook_name": "record_refresh" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null } }, "exposures": {}, diff --git a/tests/goldens/compiler/seed/5.json b/tests/goldens/compiler/seed/5.json index 164c7367b7..207323880c 100644 --- a/tests/goldens/compiler/seed/5.json +++ b/tests/goldens/compiler/seed/5.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro name collision for 'adjust_0': macros/python/adjust_0.py and macros/python/duplicate_adjust_0.py" + "message": "Model file models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'" } ] }, @@ -20,7 +20,7 @@ "phase": "compile", "severity": "error", "code": "P001", - "message": "Macro name collision for 'adjust_0': macros/python/adjust_0.py and macros/python/duplicate_adjust_0.py" + "message": "Model file models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'" } ] }, @@ -37,7 +37,7 @@ "Project assembly OK ()", "Project discovery OK ()", "Compiling project...", - "error[P001]: Macro name collision for 'adjust_0': macros/python/adjust_0.py and macros/python/duplicate_adjust_0.py", + "error[P001]: Model file models/fulfillment/staging/stg_fulfillment_2.sql references unknown model 'missing_model'", "", "" ] diff --git a/tests/goldens/compiler/seed/6.json b/tests/goldens/compiler/seed/6.json index 6b89a5755a..491deba8ac 100644 --- a/tests/goldens/compiler/seed/6.json +++ b/tests/goldens/compiler/seed/6.json @@ -263,24 +263,12 @@ " )", "" ], - "audits/generic/fulfillment_summary_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"fulfillment_summary_0\")", - "WHERE id IS NULL", - "" - ], "audits/generic/sales_summary_0/not_null__id.sql": [ "SELECT id", "FROM __ref(\"sales_summary_0\")", "WHERE id IS NULL", "" ], - "audits/generic/sales_summary_1/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"sales_summary_1\")", - "WHERE id IS NULL", - "" - ], "audits/generic/shaped_stg_inventory_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"shaped_stg_inventory_2\")", @@ -300,15 +288,33 @@ "WHERE id IS NULL", "" ], + "audits/generic/stg_fulfillment_1/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"stg_fulfillment_1\")", + "WHERE id IS NULL", + "" + ], "audits/generic/stg_fulfillment_2/not_null__id.sql": [ "SELECT id", "FROM __ref(\"stg_fulfillment_2\")", "WHERE id IS NULL", "" ], - "audits/generic/stg_inventory_1/not_null__id.sql": [ + "audits/generic/stg_inventory_0/not_null__id.sql": [ "SELECT id", - "FROM __ref(\"stg_inventory_1\")", + "FROM __ref(\"stg_inventory_0\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/stg_inventory_2/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"stg_inventory_2\")", + "WHERE id IS NULL", + "" + ], + "audits/generic/stg_sales_0/not_null__id.sql": [ + "SELECT id", + "FROM __ref(\"stg_sales_0\")", "WHERE id IS NULL", "" ], @@ -445,8 +451,7 @@ " t.status,", " t.created_at,", " 3 AS priority,", - " 'Ελληνικά orders' AS threshold_0_label,", - " '東京 warehouse' AS site_label", + " 'Ελληνικά orders' AS threshold_0_label", "FROM __source(\"raw_events_0\") t", "" ], @@ -455,7 +460,8 @@ " t.id,", " t.amount,", " t.status,", - " t.created_at", + " t.created_at,", + " '東京 warehouse' AS site_label", "FROM __source(\"raw_events_0\") t", "" ], @@ -493,8 +499,7 @@ " t.id,", " t.amount,", " t.status,", - " t.created_at,", - " '東京 warehouse' AS site_label", + " t.created_at", "FROM __source(\"raw_events_0\") t", "" ], @@ -513,8 +518,7 @@ " t.amount,", " t.status,", " t.created_at,", - " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_0_amount,", - " '東京 warehouse' AS site_label", + " ROUND(ROUND((t.amount * 2), 2), 2) AS adjust_0_amount", "FROM __source(\"raw_events_0\") t", "" ], @@ -1591,8 +1595,8 @@ "channel": "café ☕ counter" }, "relative_path": "models/features/_sqlbuild/_hooks/python/notify.py", - "definition_hash": "55440ff19f0c4f231ad57d453227a3c9d584b81234ee4b3338a39ccdf59814a8", - "version_hash": "03b4f786f8ab2736e5be2e4de5016bd16ea44d84beca000ec2a53a397e503eb6" + "definition_hash": "4669f6863eaccfebdb6aa5286a58eb944d8b0142ea2bc8e6678cce4efb35bf7e", + "version_hash": "80b0b3a25244f0def68efcbecd29182bfa91d76b9272c4d2147d08ae88260fa2" } ] } @@ -1951,18 +1955,7 @@ "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'main.fulfillment_summary_0' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'main.fulfillment_summary_0' AS refreshed", - "transaction": true, - "index": 1 - } - ], + "post-hook": [], "pre-hook": [], "quoting": {}, "column_types": {}, @@ -1986,41 +1979,8 @@ "marts" ], "description": "Summary of fulfillment activity 0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'main.fulfillment_summary_0' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "Ελληνικά orders" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'main.fulfillment_summary_0' AS refreshed" - } - ] - } - } - }, + "columns": {}, + "meta": {}, "group": null, "docs": { "show": true, @@ -2177,7 +2137,17 @@ "staging" ], "description": "Staged fulfillment events 1 (東京 warehouse)", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": {}, "group": null, "docs": { @@ -2555,7 +2525,17 @@ "staging" ], "description": "Staged inventory events 0 (Ελληνικά orders)", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": {}, "group": null, "docs": { @@ -2629,17 +2609,7 @@ "staging" ], "description": "Staged inventory events 1", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, + "columns": {}, "meta": {}, "group": null, "docs": { @@ -2713,7 +2683,17 @@ "staging" ], "description": "Staged inventory events 2", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": {}, "group": null, "docs": { @@ -2930,7 +2910,7 @@ "persist_docs": {}, "post-hook": [ { - "sql": "SELECT 'main.sales_summary_0' AS refreshed_relation, '東京 warehouse' AS refresh_label", + "sql": "SELECT 'main.sales_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", "transaction": true, "index": 0 }, @@ -2977,13 +2957,13 @@ "post_hooks": [ { "type": "sql", - "statement": "SELECT 'main.sales_summary_0' AS refreshed_relation, '東京 warehouse' AS refresh_label", + "statement": "SELECT 'main.sales_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", "name": "record_refresh", "relative_path": "hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", - "label": "東京 warehouse" + "label": "naïve résumé" }, "description": "Record a refresh for one relation" }, @@ -3042,7 +3022,18 @@ "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, - "post-hook": [], + "post-hook": [ + { + "sql": "SELECT 'main.sales_summary_1' AS refreshed_relation, 'café ☕ counter' AS refresh_label", + "transaction": true, + "index": 0 + }, + { + "sql": "SELECT 'main.sales_summary_1' AS refreshed", + "transaction": true, + "index": 1 + } + ], "pre-hook": [], "quoting": {}, "column_types": {}, @@ -3063,18 +3054,31 @@ }, "tags": [], "description": "Summary of sales activity 1 (café ☕ counter)", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] + "columns": {}, + "meta": { + "sqlbuild": { + "lifecycle_hooks": { + "post_hooks": [ + { + "type": "sql", + "statement": "SELECT 'main.sales_summary_1' AS refreshed_relation, 'café ☕ counter' AS refresh_label", + "name": "record_refresh", + "relative_path": "hooks/sql/record_refresh.sql", + "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", + "kwargs": { + "relation": "@@CTX:destination.qualified", + "label": "café ☕ counter" + }, + "description": "Record a refresh for one relation" + }, + { + "type": "sql", + "statement": "SELECT 'main.sales_summary_1' AS refreshed" + } + ] + } } }, - "meta": {}, "group": null, "docs": { "show": true, @@ -3148,7 +3152,17 @@ "staging" ], "description": "Staged sales events 0", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": {}, "group": null, "docs": { diff --git a/tests/goldens/compiler/seed/8.json b/tests/goldens/compiler/seed/8.json index b897cf2d2d..d7a3421f73 100644 --- a/tests/goldens/compiler/seed/8.json +++ b/tests/goldens/compiler/seed/8.json @@ -2,2769 +2,44 @@ "commands": [ { "label": "compile", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "D002", + "message": "MODEL(...) in '/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111" + } + ] }, { "label": "compile-store-warm", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + { + "phase": "compile", + "severity": "error", + "code": "D002", + "message": "MODEL(...) in '/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111" + } + ] }, { "label": "plan", - "exit_code": 0, - "diagnostics": [] + "exit_code": 1, + "diagnostics": [ + "Project discovery START", + "Project assembly START", + "Declaration parsing START", + "Declaration parsing FAIL ()", + "Project assembly FAIL ()", + "Project discovery FAIL ()", + "error[D002]: MODEL(...) in '/models/support/marts/support_summary_2.sql' contains invalid SQLBuild header syntax: expected key at position 111", + "", + "" + ] } ], - "compiled": { - "audits/generic/audited_stg_support_0/id_present__id.sql": [ - "SELECT id", - "FROM __ref(\"audited_stg_support_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/checked_stg_support_0/accepted_values__status.sql": [ - "SELECT status", - "FROM __ref(\"checked_stg_support_0\")", - "WHERE status IS NOT NULL", - " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", - "" - ], - "audits/generic/checked_stg_support_0/expression_is_true.sql": [ - "SELECT *", - "FROM __ref(\"checked_stg_support_0\")", - "WHERE NOT (amount >= -1000)", - "" - ], - "audits/generic/checked_stg_support_0/relationships__id.sql": [ - "SELECT id", - "FROM __ref(\"checked_stg_support_0\")", - "WHERE id IS NOT NULL", - " AND id NOT IN (", - " SELECT id", - " FROM __ref(\"stg_support_0\")", - " WHERE id IS NOT NULL", - " )", - "" - ], - "audits/generic/configured_events/accepted_values__id.sql": [ - "SELECT id", - "FROM __source(\"configured_events\")", - "WHERE id IS NOT NULL", - " AND id NOT IN ('1')", - "" - ], - "audits/generic/configured_stg_support_0/accepted_values__status.sql": [ - "SELECT status", - "FROM __ref(\"configured_stg_support_0\")", - "WHERE status IS NOT NULL", - " AND status NOT IN ('placed', 'shipped')", - "" - ], - "audits/generic/configured_stg_support_0/configured_amount_floor.sql": [ - "SELECT *", - "FROM __ref(\"configured_stg_support_0\")", - "WHERE amount < -40", - "" - ], - "audits/generic/configured_stg_support_0/configured_id_present__id.sql": [ - "SELECT id", - "FROM __ref(\"configured_stg_support_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/configured_stg_support_0/unique__id.sql": [ - "SELECT id, COUNT(*) AS duplicate_count", - "FROM __ref(\"configured_stg_support_0\")", - "WHERE id IS NOT NULL", - "GROUP BY id", - "HAVING COUNT(*) > 1", - "" - ], - "audits/generic/labelled_stg_support_0/tidy_status__status.sql": [ - "SELECT *", - "FROM __ref(\"labelled_stg_support_0\")", - "WHERE status <> LOWER(TRIM(status))", - "" - ], - "audits/generic/shaped_stg_support_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"shaped_stg_support_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/stg_support_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"stg_support_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/support_summary_0/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"support_summary_0\")", - "WHERE id IS NULL", - "" - ], - "audits/generic/support_summary_1/not_null__id.sql": [ - "SELECT id", - "FROM __ref(\"support_summary_1\")", - "WHERE id IS NULL", - "" - ], - "audits/singular/labelled_channels_match.sql": [ - "SELECT l.id", - "FROM __ref(\"labelled_stg_support_0\") l", - "JOIN __ref(\"channel_labels\") c ON l.id = c.id", - "WHERE l.status = c.channel", - "" - ], - "functions/sql/configured_label.sql": [ - "CREATE OR REPLACE MACRO ci_checks.configured_label(raw_status) AS (", - "UPPER(raw_status)", - ")", - "" - ], - "functions/sql/tidy_status.sql": [ - "CREATE OR REPLACE MACRO ci_checks.tidy_status(raw_status) AS (", - "LOWER(TRIM(raw_status))", - ")", - "" - ], - "models/analysis/checked_stg_support_0.sql": [ - "SELECT id, amount, status", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/analysis/pivot_input_stg_support_0.sql": [ - "SELECT CAST(id AS INTEGER) AS id, CAST(status AS VARCHAR) AS status, amount", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/analysis/pivoted_stg_support_0.sql": [ - "PIVOT __ref(\"pivot_input_stg_support_0\")", - "ON status", - "USING MAX(amount)", - "GROUP BY id", - "" - ], - "models/analysis/unanalysed_stg_support_0.sql": [ - "SELECT a.id, a.amount", - "FROM __ref(\"stg_support_0\") AS a", - "JOIN __ref(\"stg_support_0\") AS b NEAREST 1 BY DISTANCE abs(a.amount - b.amount)", - "" - ], - "models/features/append_stg_support_0.sql": [ - "SELECT id, amount, status, created_at", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/features/audited_stg_support_0.sql": [ - "SELECT id, amount", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/features/batched_rolling_window_stg_support_0.sql": [ - "SELECT CAST(created_at AS DATE) AS created_at, SUM(amount) AS amount", - "FROM __ref(\"stg_support_0\")", - "GROUP BY CAST(created_at AS DATE)", - "" - ], - "models/features/hooked_stg_support_0.sql": [ - "SELECT id, amount", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/features/product_labels.sql": [ - "SELECT id, label", - "FROM __source(\"loaded_products\")", - "" - ], - "models/features/shaped_stg_support_0.sql": [ - "SELECT CAST(id AS INTEGER) AS id, status", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/features/taxed_stg_support_0.sql": [ - "SELECT id, ROUND(amount * 1.2, 2) AS taxed, ROUND(amount, 1) AS rounded", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/rendering/bounded_stg_support_0.sql": [ - "SELECT id, amount, created_at", - "FROM __ref(\"stg_support_0\")", - "WHERE created_at >= __cursor_start()", - " AND created_at < __cursor_end()", - "" - ], - "models/rendering/channel_labels.sql": [ - "SELECT id, channel", - "FROM __source(\"labelled_channels\")", - "" - ], - "models/rendering/configured_stg_support_0.sql": [ - "SELECT id, amount, status", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/rendering/labelled_stg_support_0.sql": [ - "SELECT id, LOWER(TRIM(status)) AS status,", - " __udf(\"tidy_status\")(status) AS tidied", - "FROM __ref(\"stg_support_0\")", - "" - ], - "models/rendering/latest_raw_events_1.sql": [ - "SELECT id, amount", - "FROM (SELECT id, amount FROM __source(\"raw_events_1\") ORDER BY id DESC LIMIT 2) AS latest", - "" - ], - "models/rendering/unioned_event_ids.sql": [ - "SELECT id", - "FROM (SELECT id FROM __ref(\"stg_support_0\") UNION ALL SELECT id FROM __ref(\"stg_support_0\")) AS unioned", - "" - ], - "models/support/marts/support_summary_0.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount + 50 AS threshold_2_amount,", - " (t.amount * (1 - 0.15)) AS adjust_0_amount,", - " (t.amount + 2 + 1) AS adjust_2_amount", - "FROM __ref(\"stg_support_0\") t", - "WHERE t.status <> 'placed'", - "" - ], - "models/support/marts/support_summary_1.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount + 237 AS threshold_0_amount,", - " (t.amount * (1 - 0.15)) AS adjust_0_amount,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " 'naïve résumé' AS site_label", - "FROM __ref(\"stg_support_0\") t", - "" - ], - "models/support/marts/support_summary_2.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount * 0.15 AS threshold_1_amount,", - " t.amount + 50 AS threshold_2_amount,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " (t.amount + 2 + 1) AS adjust_2_amount", - "FROM __ref(\"stg_support_0\") t", - "" - ], - "models/support/staging/stg_support_0.sql": [ - "SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount + 237 AS threshold_0_amount,", - " t.amount + 50 AS threshold_2_amount,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " (t.amount + 2 + 1) AS adjust_2_amount", - "FROM __source(\"raw_events_0\") t", - "WHERE t.status <> 'expédié'", - "" - ], - "tests/_chain_/labelled_stg_support_0__stg_support_0/test_labelled_stg_support_0.sql": [ - "WITH __source__raw_events_0 AS (SELECT 1 AS id, CAST(1 AS DOUBLE) AS amount, 'placed' AS status, TIMESTAMP '2026-01-01 00:00:00' AS created_at UNION ALL SELECT 2 AS id, CAST(2 AS DOUBLE) AS amount, 'placed' AS status, TIMESTAMP '2026-01-02 00:00:00' AS created_at),", - "__ref__stg_support_0 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount + 237 AS threshold_0_amount,", - " t.amount + 50 AS threshold_2_amount,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " (t.amount + 2 + 1) AS adjust_2_amount", - "FROM __source__raw_events_0 t", - "WHERE t.status <> 'expédié'),", - "__ref__labelled_stg_support_0 AS (SELECT id, LOWER(TRIM(status)) AS status,", - " ci_checks.tidy_status(status) AS tidied", - "FROM __ref__stg_support_0),", - "__actual__labelled_stg_support_0 AS (SELECT * FROM __ref__labelled_stg_support_0),", - "__expected__labelled_stg_support_0 AS (SELECT 1 AS id, LOWER(TRIM('placed')) AS status", - " UNION ALL", - " SELECT 2 AS id, 'placed' AS status)", - "SELECT 1 AS step_index, 'labelled_stg_support_0' AS model_name, (SELECT COUNT(*) FROM __actual__labelled_stg_support_0) AS actual_count, (SELECT COUNT(*) FROM __expected__labelled_stg_support_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __actual__labelled_stg_support_0 EXCEPT SELECT id, status FROM __expected__labelled_stg_support_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __expected__labelled_stg_support_0 EXCEPT SELECT id, status FROM __actual__labelled_stg_support_0) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/macro doubles_amounts/doubles_amounts.sql": [ - "WITH input_values AS (SELECT 4 AS amount),", - "__actual__macro_doubles_amounts AS (SELECT (amount * 2) AS doubled", - " FROM input_values),", - "__expected__macro_doubles_amounts AS (SELECT 8 AS doubled)", - "SELECT 0 AS step_index, 'macro doubles_amounts' AS model_name, (SELECT COUNT(*) FROM __actual__macro_doubles_amounts) AS actual_count, (SELECT COUNT(*) FROM __expected__macro_doubles_amounts) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__macro_doubles_amounts EXCEPT SELECT * FROM __expected__macro_doubles_amounts) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__macro_doubles_amounts EXCEPT SELECT * FROM __actual__macro_doubles_amounts) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/macro taxes_amounts/taxes_amounts.sql": [ - "WITH input_values AS (SELECT 10 AS amount),", - "__actual__macro_taxes_amounts AS (SELECT ROUND(amount * 1.2, 2) AS taxed", - " FROM input_values),", - "__expected__macro_taxes_amounts AS (SELECT 12.0 AS taxed)", - "SELECT 0 AS step_index, 'macro taxes_amounts' AS model_name, (SELECT COUNT(*) FROM __actual__macro_taxes_amounts) AS actual_count, (SELECT COUNT(*) FROM __expected__macro_taxes_amounts) AS expected_count, (SELECT COUNT(*) FROM (SELECT * FROM __actual__macro_taxes_amounts EXCEPT SELECT * FROM __expected__macro_taxes_amounts) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT * FROM __expected__macro_taxes_amounts EXCEPT SELECT * FROM __actual__macro_taxes_amounts) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/stg_support_0/test_stg_support_0.sql": [ - "WITH __source__raw_events_0 AS (SELECT 1 AS id, CAST(10 AS DOUBLE) AS amount, 'placed' AS status,", - " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__stg_support_0 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount + 237 AS threshold_0_amount,", - " t.amount + 50 AS threshold_2_amount,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " (t.amount + 2 + 1) AS adjust_2_amount", - "FROM __source__raw_events_0 t", - "WHERE t.status <> 'expédié'),", - "__actual__stg_support_0 AS (SELECT * FROM __ref__stg_support_0),", - "__expected__stg_support_0 AS (SELECT 1 AS id, 'placed' AS status)", - "SELECT 0 AS step_index, 'stg_support_0' AS model_name, (SELECT COUNT(*) FROM __actual__stg_support_0) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_support_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __actual__stg_support_0 EXCEPT SELECT id, status FROM __expected__stg_support_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id, status FROM __expected__stg_support_0 EXCEPT SELECT id, status FROM __actual__stg_support_0) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/tests/unit/test_stg_support_0_cases/block_1__labelled.sql": [ - "WITH __source__raw_events_0 AS (SELECT 1 AS id, CAST(2.25 AS DOUBLE) AS amount,", - " 'café ☕ counter' AS status,", - " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__stg_support_0 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount + 237 AS threshold_0_amount,", - " t.amount + 50 AS threshold_2_amount,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " (t.amount + 2 + 1) AS adjust_2_amount", - "FROM __source__raw_events_0 t", - "WHERE t.status <> 'expédié'),", - "__actual__stg_support_0 AS (SELECT * FROM __ref__stg_support_0),", - "__expected__stg_support_0 AS (SELECT 1 AS id)", - "SELECT 0 AS step_index, 'stg_support_0' AS model_name, (SELECT COUNT(*) FROM __actual__stg_support_0) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_support_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id FROM __actual__stg_support_0 EXCEPT SELECT id FROM __expected__stg_support_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id FROM __expected__stg_support_0 EXCEPT SELECT id FROM __actual__stg_support_0) AS __sqlbuild_missing) AS missing_count", - "" - ], - "tests/tests/unit/test_stg_support_0_cases/block_1__placed.sql": [ - "WITH __source__raw_events_0 AS (SELECT 1 AS id, CAST(1.5 AS DOUBLE) AS amount,", - " 'placed' AS status,", - " TIMESTAMP '2026-01-01 00:00:00' AS created_at),", - "__ref__stg_support_0 AS (SELECT", - " t.id,", - " t.amount,", - " t.status,", - " t.created_at,", - " t.amount + 237 AS threshold_0_amount,", - " t.amount + 50 AS threshold_2_amount,", - " (t.amount + LENGTH('east')) AS adjust_1_amount,", - " (t.amount + 2 + 1) AS adjust_2_amount", - "FROM __source__raw_events_0 t", - "WHERE t.status <> 'expédié'),", - "__actual__stg_support_0 AS (SELECT * FROM __ref__stg_support_0),", - "__expected__stg_support_0 AS (SELECT 1 AS id)", - "SELECT 0 AS step_index, 'stg_support_0' AS model_name, (SELECT COUNT(*) FROM __actual__stg_support_0) AS actual_count, (SELECT COUNT(*) FROM __expected__stg_support_0) AS expected_count, (SELECT COUNT(*) FROM (SELECT id FROM __actual__stg_support_0 EXCEPT SELECT id FROM __expected__stg_support_0) AS __sqlbuild_mismatch) AS unexpected_count, (SELECT COUNT(*) FROM (SELECT id FROM __expected__stg_support_0 EXCEPT SELECT id FROM __actual__stg_support_0) AS __sqlbuild_missing) AS missing_count", - "" - ] - }, - "manifest": { - "nodes": { - "model.generated_8.checked_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "checked_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/analysis/checked_stg_support_0.sql", - "original_file_path": "models/analysis/checked_stg_support_0.sql", - "unique_id": "model.generated_8.checked_stg_support_0", - "fqn": [ - "generated_8", - "models", - "analysis", - "checked_stg_support_0" - ], - "alias": "checked_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": [ - "id" - ], - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Metadata-checked copy of stg_support_0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.checked_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.pivot_input_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "pivot_input_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/analysis/pivot_input_stg_support_0.sql", - "original_file_path": "models/analysis/pivot_input_stg_support_0.sql", - "unique_id": "model.generated_8.pivot_input_stg_support_0", - "fqn": [ - "generated_8", - "models", - "analysis", - "pivot_input_stg_support_0" - ], - "alias": "pivot_input_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Contracted pivot input from stg_support_0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.pivot_input_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.pivoted_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "pivoted_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/analysis/pivoted_stg_support_0.sql", - "original_file_path": "models/analysis/pivoted_stg_support_0.sql", - "unique_id": "model.generated_8.pivoted_stg_support_0", - "fqn": [ - "generated_8", - "models", - "analysis", - "pivoted_stg_support_0" - ], - "alias": "pivoted_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Amounts of stg_support_0 pivoted by status", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "dynamic_columns": [ - { - "name": "status_amounts", - "pivot_column": "status", - "value_column": "amount", - "aggregate": "MAX", - "type": "DOUBLE", - "name_pattern": null - } - ] - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.pivoted_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.pivot_input_stg_support_0" - ] - } - }, - "model.generated_8.unanalysed_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "unanalysed_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/analysis/unanalysed_stg_support_0.sql", - "original_file_path": "models/analysis/unanalysed_stg_support_0.sql", - "unique_id": "model.generated_8.unanalysed_stg_support_0", - "fqn": [ - "generated_8", - "models", - "analysis", - "unanalysed_stg_support_0" - ], - "alias": "unanalysed_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Copy of stg_support_0 that SQL analysis cannot parse", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.unanalysed_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.append_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "append_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/features/append_stg_support_0.sql", - "original_file_path": "models/features/append_stg_support_0.sql", - "unique_id": "model.generated_8.append_stg_support_0", - "fqn": [ - "generated_8", - "models", - "features", - "append_stg_support_0" - ], - "alias": "append_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "incremental", - "incremental_strategy": "append", - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Incremental append copy of stg_support_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.append_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.audited_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "audited_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/features/audited_stg_support_0.sql", - "original_file_path": "models/features/audited_stg_support_0.sql", - "unique_id": "model.generated_8.audited_stg_support_0", - "fqn": [ - "generated_8", - "models", - "features", - "audited_stg_support_0" - ], - "alias": "audited_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Factory-audited copy of stg_support_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.audited_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.batched_rolling_window_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "batched_rolling_window_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/features/batched_rolling_window_stg_support_0.sql", - "original_file_path": "models/features/batched_rolling_window_stg_support_0.sql", - "unique_id": "model.generated_8.batched_rolling_window_stg_support_0", - "fqn": [ - "generated_8", - "models", - "features", - "batched_rolling_window_stg_support_0" - ], - "alias": "batched_rolling_window_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "incremental", - "incremental_strategy": "delete_insert", - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Microbatched rolling_window totals of stg_support_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.batched_rolling_window_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.hooked_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "hooked_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/features/hooked_stg_support_0.sql", - "original_file_path": "models/features/hooked_stg_support_0.sql", - "unique_id": "model.generated_8.hooked_stg_support_0", - "fqn": [ - "generated_8", - "models", - "features", - "hooked_stg_support_0" - ], - "alias": "hooked_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Hooked copy of stg_support_0", - "columns": {}, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "python", - "name": "note_refresh", - "kwargs": { - "channel": "東京 warehouse" - }, - "relative_path": "models/features/_sqlbuild/_hooks/python/notify.py", - "definition_hash": "55440ff19f0c4f231ad57d453227a3c9d584b81234ee4b3338a39ccdf59814a8", - "version_hash": "03b4f786f8ab2736e5be2e4de5016bd16ea44d84beca000ec2a53a397e503eb6" - } - ] - } - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.hooked_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.product_labels": { - "database": null, - "schema": "ci_checks", - "name": "product_labels", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/features/product_labels.sql", - "original_file_path": "models/features/product_labels.sql", - "unique_id": "model.generated_8.product_labels", - "fqn": [ - "generated_8", - "models", - "features", - "product_labels" - ], - "alias": "product_labels", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Product labels from the loader", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.product_labels", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_8.loaded_products" - ] - } - }, - "model.generated_8.shaped_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "shaped_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/features/shaped_stg_support_0.sql", - "original_file_path": "models/features/shaped_stg_support_0.sql", - "unique_id": "model.generated_8.shaped_stg_support_0", - "fqn": [ - "generated_8", - "models", - "features", - "shaped_stg_support_0" - ], - "alias": "shaped_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Schema-shaped copy of stg_support_0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.shaped_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.taxed_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "taxed_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/features/taxed_stg_support_0.sql", - "original_file_path": "models/features/taxed_stg_support_0.sql", - "unique_id": "model.generated_8.taxed_stg_support_0", - "fqn": [ - "generated_8", - "models", - "features", - "taxed_stg_support_0" - ], - "alias": "taxed_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Taxed copy of stg_support_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.taxed_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.bounded_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "bounded_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/rendering/bounded_stg_support_0.sql", - "original_file_path": "models/rendering/bounded_stg_support_0.sql", - "unique_id": "model.generated_8.bounded_stg_support_0", - "fqn": [ - "generated_8", - "models", - "rendering", - "bounded_stg_support_0" - ], - "alias": "bounded_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "incremental", - "incremental_strategy": "delete_insert", - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": [ - "id" - ], - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Cursor-bounded copy of stg_support_0", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.bounded_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.channel_labels": { - "database": null, - "schema": "ci_checks", - "name": "channel_labels", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/rendering/channel_labels.sql", - "original_file_path": "models/rendering/channel_labels.sql", - "unique_id": "model.generated_8.channel_labels", - "fqn": [ - "generated_8", - "models", - "rendering", - "channel_labels" - ], - "alias": "channel_labels", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Normalised channel labels", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.channel_labels", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_8.labelled_channels" - ] - } - }, - "model.generated_8.configured_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "configured_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/rendering/configured_stg_support_0.sql", - "original_file_path": "models/rendering/configured_stg_support_0.sql", - "unique_id": "model.generated_8.configured_stg_support_0", - "fqn": [ - "generated_8", - "models", - "rendering", - "configured_stg_support_0" - ], - "alias": "configured_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "release" - ], - "meta": {}, - "group": null, - "materialized": "table", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "release" - ], - "description": "Configured copy of stg_support_0 (réglé)", - "columns": { - "id": { - "name": "id", - "description": "Row key", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "Montant réglé", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.configured_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.labelled_stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "labelled_stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/rendering/labelled_stg_support_0.sql", - "original_file_path": "models/rendering/labelled_stg_support_0.sql", - "unique_id": "model.generated_8.labelled_stg_support_0", - "fqn": [ - "generated_8", - "models", - "rendering", - "labelled_stg_support_0" - ], - "alias": "labelled_stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Labelled copy of stg_support_0", - "columns": { - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.labelled_stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.tidy_status", - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.latest_raw_events_1": { - "database": null, - "schema": "ci_checks", - "name": "latest_raw_events_1", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/rendering/latest_raw_events_1.sql", - "original_file_path": "models/rendering/latest_raw_events_1.sql", - "unique_id": "model.generated_8.latest_raw_events_1", - "fqn": [ - "generated_8", - "models", - "rendering", - "latest_raw_events_1" - ], - "alias": "latest_raw_events_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Newest rows of raw_events_1", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.latest_raw_events_1", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_8.raw_events_1" - ] - } - }, - "model.generated_8.unioned_event_ids": { - "database": null, - "schema": "ci_checks", - "name": "unioned_event_ids", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/rendering/unioned_event_ids.sql", - "original_file_path": "models/rendering/unioned_event_ids.sql", - "unique_id": "model.generated_8.unioned_event_ids", - "fqn": [ - "generated_8", - "models", - "rendering", - "unioned_event_ids" - ], - "alias": "unioned_event_ids", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Ids from two staged relations", - "columns": {}, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.unioned_event_ids", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.support_summary_0": { - "database": null, - "schema": "ci_checks", - "name": "support_summary_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/support/marts/support_summary_0.sql", - "original_file_path": "models/support/marts/support_summary_0.sql", - "unique_id": "model.generated_8.support_summary_0", - "fqn": [ - "generated_8", - "models", - "support", - "marts", - "support_summary_0" - ], - "alias": "support_summary_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'ci_checks.support_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'ci_checks.support_summary_0' AS refreshed", - "transaction": true, - "index": 1 - } - ], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Summary of support activity 0", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_0' AS refreshed_relation, 'naïve résumé' AS refresh_label", - "name": "record_refresh", - "relative_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "naïve résumé" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_0' AS refreshed" - } - ] - } - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.support_summary_0", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.support_summary_1": { - "database": null, - "schema": "ci_checks", - "name": "support_summary_1", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/support/marts/support_summary_1.sql", - "original_file_path": "models/support/marts/support_summary_1.sql", - "unique_id": "model.generated_8.support_summary_1", - "fqn": [ - "generated_8", - "models", - "support", - "marts", - "support_summary_1" - ], - "alias": "support_summary_1", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'ci_checks.support_summary_1' AS refreshed_relation, '東京 warehouse' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'ci_checks.support_summary_1' AS refreshed", - "transaction": true, - "index": 1 - } - ], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Summary of support activity 1", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_1' AS refreshed_relation, '東京 warehouse' AS refresh_label", - "name": "record_refresh", - "relative_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "東京 warehouse" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_1' AS refreshed" - } - ] - } - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.support_summary_1", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.support_summary_2": { - "database": null, - "schema": "ci_checks", - "name": "support_summary_2", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/support/marts/support_summary_2.sql", - "original_file_path": "models/support/marts/support_summary_2.sql", - "unique_id": "model.generated_8.support_summary_2", - "fqn": [ - "generated_8", - "models", - "support", - "marts", - "support_summary_2" - ], - "alias": "support_summary_2", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'ci_checks.support_summary_2' AS refreshed_relation, 'Zürich – depot' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'ci_checks.support_summary_2' AS refreshed", - "transaction": true, - "index": 1 - } - ], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [], - "description": "Summary of support activity 2", - "columns": {}, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_2' AS refreshed_relation, 'Zürich – depot' AS refresh_label", - "name": "record_refresh", - "relative_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "Zürich – depot" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'ci_checks.support_summary_2' AS refreshed" - } - ] - } - } - }, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.support_summary_2", - "depends_on": { - "macros": [], - "nodes": [ - "model.generated_8.stg_support_0" - ] - } - }, - "model.generated_8.stg_support_0": { - "database": null, - "schema": "ci_checks", - "name": "stg_support_0", - "resource_type": "model", - "package_name": "generated_8", - "path": "models/support/staging/stg_support_0.sql", - "original_file_path": "models/support/staging/stg_support_0.sql", - "unique_id": "model.generated_8.stg_support_0", - "fqn": [ - "generated_8", - "models", - "support", - "staging", - "stg_support_0" - ], - "alias": "stg_support_0", - "config": { - "enabled": true, - "alias": null, - "schema": "ci_checks", - "database": null, - "tags": [ - "staging" - ], - "meta": {}, - "group": null, - "materialized": "view", - "incremental_strategy": null, - "merge_exclude_columns": null, - "persist_docs": {}, - "post-hook": [], - "pre-hook": [], - "quoting": {}, - "column_types": {}, - "full_refresh": null, - "unique_key": null, - "on_schema_change": "ignore", - "on_configuration_change": "apply", - "grants": {}, - "packages": [], - "docs": { - "show": true, - "node_color": null - }, - "contract": { - "enforced": false, - "alias_types": true - } - }, - "tags": [ - "staging" - ], - "description": "Staged support events 0 (東京 warehouse)", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "group": null, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "build_path": null, - "unrendered_config": {}, - "config_call_dict": {}, - "unrendered_config_call_dict": {}, - "relation_name": "ci_checks.stg_support_0", - "depends_on": { - "macros": [], - "nodes": [ - "source.generated_8.raw_events_0" - ] - } - } - }, - "sources": { - "source.generated_8.configured_events": { - "database": null, - "schema": "", - "name": "configured_events", - "resource_type": "source", - "package_name": "generated_8", - "path": "sources/configured.yml", - "original_file_path": "sources/configured.yml", - "unique_id": "source.generated_8.configured_events", - "fqn": [ - "generated_8", - "configured_events" - ], - "source_name": "configured_events", - "source_description": "", - "loader": "", - "identifier": "configured_events", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Configured feed events", - "columns": { - "id": { - "name": "id", - "description": "Key id", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "owner": "orders team" - }, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_8.labelled_channels": { - "database": null, - "schema": "", - "name": "labelled_channels", - "resource_type": "source", - "package_name": "generated_8", - "path": "sources/labelled.yml", - "original_file_path": "sources/labelled.yml", - "unique_id": "source.generated_8.labelled_channels", - "fqn": [ - "generated_8", - "labelled_channels" - ], - "source_name": "labelled_channels", - "source_description": "", - "loader": "", - "identifier": "labelled_channels", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Channel labels normalised in the source expression.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "channel": { - "name": "channel", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_8.loaded_products": { - "database": null, - "schema": "ci_checks", - "name": "loaded_products", - "resource_type": "source", - "package_name": "generated_8", - "path": "sources/managed.yml", - "original_file_path": "sources/managed.yml", - "unique_id": "source.generated_8.loaded_products", - "fqn": [ - "generated_8", - "loaded_products" - ], - "source_name": "loaded_products", - "source_description": "", - "loader": "", - "identifier": "loaded_products", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Products loaded by a project loader.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "label": { - "name": "label", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": { - "sqlbuild": { - "loader": "loaded_products", - "auto_load": false, - "write_strategy": "table" - } - }, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_8.raw_events_0": { - "database": null, - "schema": "", - "name": "raw_events_0", - "resource_type": "source", - "package_name": "generated_8", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", - "unique_id": "source.generated_8.raw_events_0", - "fqn": [ - "generated_8", - "raw_events_0" - ], - "source_name": "raw_events_0", - "source_description": "", - "loader": "", - "identifier": "raw_events_0", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Generated event feed 0.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - }, - "created_at": { - "name": "created_at", - "description": "", - "meta": {}, - "data_type": "TIMESTAMP", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - }, - "source.generated_8.raw_events_1": { - "database": null, - "schema": "", - "name": "raw_events_1", - "resource_type": "source", - "package_name": "generated_8", - "path": "sources/raw.yml", - "original_file_path": "sources/raw.yml", - "unique_id": "source.generated_8.raw_events_1", - "fqn": [ - "generated_8", - "raw_events_1" - ], - "source_name": "raw_events_1", - "source_description": "", - "loader": "", - "identifier": "raw_events_1", - "quoting": {}, - "loaded_at_field": null, - "freshness": null, - "external": null, - "description": "Generated event feed 1.", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": "INTEGER", - "constraints": [], - "quote": null, - "tags": [] - }, - "amount": { - "name": "amount", - "description": "", - "meta": {}, - "data_type": "DOUBLE", - "constraints": [], - "quote": null, - "tags": [] - }, - "status": { - "name": "status", - "description": "", - "meta": {}, - "data_type": "VARCHAR", - "constraints": [], - "quote": null, - "tags": [] - }, - "created_at": { - "name": "created_at", - "description": "", - "meta": {}, - "data_type": "TIMESTAMP", - "constraints": [], - "quote": null, - "tags": [] - } - }, - "meta": {}, - "source_meta": {}, - "tags": [], - "config": {}, - "patch_path": null, - "unrendered_config": {}, - "relation_name": null - } - }, - "macros": { - "macro.generated_8.tidy_label": { - "name": "tidy_label", - "resource_type": "macro", - "package_name": "generated_8", - "path": "macros/python/labels.py", - "original_file_path": "macros/python/labels.py", - "unique_id": "macro.generated_8.tidy_label", - "macro_sql": "def tidy_label(expression: str) -> str:\n \"\"\"Trim and lower-case a label.\"\"\"\n return f\"LOWER(TRIM({expression}))\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.round_amount": { - "name": "round_amount", - "resource_type": "macro", - "package_name": "generated_8", - "path": "macros/python/rounding.py", - "original_file_path": "macros/python/rounding.py", - "unique_id": "macro.generated_8.round_amount", - "macro_sql": "def round_amount(expression: str, places: int = 2) -> str:\n \"\"\"Round an amount.\"\"\"\n return f\"ROUND({expression}, {places})\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.taxed": { - "name": "taxed", - "resource_type": "macro", - "package_name": "generated_8", - "path": "macros/python/tax.py", - "original_file_path": "macros/python/tax.py", - "unique_id": "macro.generated_8.taxed", - "macro_sql": "from macros.python.rounding import round_amount\n\n\ndef taxed(expression: str) -> str:\n \"\"\"Add tax to an amount, rounded.\"\"\"\n return round_amount(f\"{expression} * 1.2\")\n", - "depends_on": { - "macros": [ - "macro.generated_8.round_amount" - ] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "global", - "sqlbuild_scope_path": null - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.latest_rows": { - "name": "latest_rows", - "resource_type": "macro", - "package_name": "generated_8", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "unique_id": "macro.generated_8.latest_rows", - "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.union_ids": { - "name": "union_ids", - "resource_type": "macro", - "package_name": "generated_8", - "path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "original_file_path": "models/rendering/_sqlbuild/_macros/python/relations.py", - "unique_id": "macro.generated_8.union_ids", - "macro_sql": "from sqlbuild.refs import SqlResourceRef\n\n\ndef union_ids(relations: list[SqlResourceRef]) -> str:\n \"\"\"Union the ids of several relations.\"\"\"\n selects = [f\"SELECT id FROM {relation}\" for relation in relations]\n return \" UNION ALL \".join(selects)\n\n\ndef latest_rows(relation: SqlResourceRef, limit: int = 2) -> str:\n \"\"\"Return the newest rows of one relation.\"\"\"\n return f\"(SELECT id, amount FROM {relation} ORDER BY id DESC LIMIT {limit})\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/rendering" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.adjust_1": { - "name": "adjust_1", - "resource_type": "macro", - "package_name": "generated_8", - "path": "models/support/_sqlbuild/macros/python/adjust_1.py", - "original_file_path": "models/support/_sqlbuild/macros/python/adjust_1.py", - "unique_id": "macro.generated_8.adjust_1", - "macro_sql": "import os\n\n\ndef adjust_1(expression: str) -> str:\n \"\"\"Tag an amount with the deployment region.\"\"\"\n region = os.environ.get(\"SQB_DIFFERENTIAL_REGION\", \"east\")\n return f\"({expression} + LENGTH('{region}'))\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/support" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.adjust_2": { - "name": "adjust_2", - "resource_type": "macro", - "package_name": "generated_8", - "path": "models/support/_sqlbuild/macros/python/adjust_2.py", - "original_file_path": "models/support/_sqlbuild/macros/python/adjust_2.py", - "unique_id": "macro.generated_8.adjust_2", - "macro_sql": "def adjust_2(expression: str) -> str:\n \"\"\"Offset an amount.\"\"\"\n return f\"({expression} + 2 + 1)\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "inherited", - "sqlbuild_scope_path": "models/support" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.adjust_0": { - "name": "adjust_0", - "resource_type": "macro", - "package_name": "generated_8", - "path": "models/support/marts/_sqlbuild/_macros/python/adjust_0.py", - "original_file_path": "models/support/marts/_sqlbuild/_macros/python/adjust_0.py", - "unique_id": "macro.generated_8.adjust_0", - "macro_sql": "def adjust_0(ctx, expression: str) -> str:\n \"\"\"Scale an amount by the configured discount.\"\"\"\n rate = ctx.vars[\"discount_rate\"]\n return f\"({expression} * (1 - {rate}))\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "models/support/marts" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.doubled": { - "name": "doubled", - "resource_type": "macro", - "package_name": "generated_8", - "path": "tests/unit/_macros/python/scaling.py", - "original_file_path": "tests/unit/_macros/python/scaling.py", - "unique_id": "macro.generated_8.doubled", - "macro_sql": "def doubled(expression: str) -> str:\n \"\"\"Double an amount.\"\"\"\n return f\"({expression} * 2)\"\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "tests/unit" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8.event_rows": { - "name": "event_rows", - "resource_type": "macro", - "package_name": "generated_8", - "path": "tests/unit/rendering/_sqlbuild/_macros/python/fixtures.py", - "original_file_path": "tests/unit/rendering/_sqlbuild/_macros/python/fixtures.py", - "unique_id": "macro.generated_8.event_rows", - "macro_sql": "def event_rows(count: int = 2) -> str:\n \"\"\"Return fixture event rows.\"\"\"\n return \" UNION ALL \".join(\n f\"SELECT {index} AS id, CAST({index} AS DOUBLE) AS amount, \"\n f\"'placed' AS status, \"\n f\"TIMESTAMP '2026-01-0{index} 00:00:00' AS created_at\"\n for index in range(1, count + 1)\n )\n", - "depends_on": { - "macros": [] - }, - "description": "", - "meta": { - "sqlbuild_visibility": "local", - "sqlbuild_scope_path": "tests/unit/rendering" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - }, - "macro.generated_8__sqlbuild_hooks.record_refresh": { - "name": "record_refresh", - "resource_type": "macro", - "package_name": "generated_8__sqlbuild_hooks", - "path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "original_file_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", - "unique_id": "macro.generated_8__sqlbuild_hooks.record_refresh", - "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "depends_on": { - "macros": [] - }, - "description": "Record a refresh for one relation", - "meta": { - "sqlbuild_resource_type": "sql_hook", - "sqlbuild_hook_name": "record_refresh" - }, - "docs": { - "show": true, - "node_color": null - }, - "patch_path": null, - "arguments": [], - "supported_languages": null - } - }, - "exposures": {}, - "metrics": {}, - "groups": {}, - "selectors": {}, - "disabled": {}, - "parent_map": { - "model.generated_8.checked_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.pivot_input_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.pivoted_stg_support_0": [ - "model.generated_8.pivot_input_stg_support_0" - ], - "model.generated_8.unanalysed_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.append_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.audited_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.batched_rolling_window_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.hooked_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.product_labels": [ - "source.generated_8.loaded_products" - ], - "model.generated_8.shaped_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.taxed_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.bounded_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.channel_labels": [ - "source.generated_8.labelled_channels" - ], - "model.generated_8.configured_stg_support_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.labelled_stg_support_0": [ - "model.generated_8.tidy_status", - "model.generated_8.stg_support_0" - ], - "model.generated_8.latest_raw_events_1": [ - "source.generated_8.raw_events_1" - ], - "model.generated_8.unioned_event_ids": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.support_summary_0": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.support_summary_1": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.support_summary_2": [ - "model.generated_8.stg_support_0" - ], - "model.generated_8.stg_support_0": [ - "source.generated_8.raw_events_0" - ], - "source.generated_8.configured_events": [], - "source.generated_8.labelled_channels": [], - "source.generated_8.loaded_products": [], - "source.generated_8.raw_events_0": [], - "source.generated_8.raw_events_1": [], - "model.generated_8.configured_label": [], - "model.generated_8.tidy_status": [] - }, - "group_map": {}, - "docs": {}, - "saved_queries": {}, - "semantic_models": {}, - "unit_tests": {} - } + "compiled": {}, + "manifest": null } diff --git a/tests/goldens/compiler/seed/9.json b/tests/goldens/compiler/seed/9.json index 5c45608e57..34e0a8f891 100644 --- a/tests/goldens/compiler/seed/9.json +++ b/tests/goldens/compiler/seed/9.json @@ -76,9 +76,9 @@ " AND status NOT IN ('placed', 'expédié', '取消', 'returned ✓')", "" ], - "audits/generic/stg_support_1/not_null__id.sql": [ + "audits/generic/stg_billing_0/not_null__id.sql": [ "SELECT id", - "FROM __ref(\"stg_support_1\")", + "FROM __ref(\"stg_billing_0\")", "WHERE id IS NULL", "" ], @@ -193,8 +193,7 @@ " t.status,", " t.created_at,", " t.amount * 2.4700 AS threshold_0_amount,", - " (t.amount + 0 + 1) AS adjust_0_amount,", - " 'Zürich – depot' AS site_label", + " (t.amount + 0 + 1) AS adjust_0_amount", "FROM __source(\"raw_events_0\") t", "" ], @@ -295,7 +294,8 @@ " t.amount,", " t.status,", " t.created_at,", - " t.amount * 2.4700 AS threshold_0_amount", + " t.amount * 2.4700 AS threshold_0_amount,", + " 'Zürich – depot' AS site_label", "FROM __source(\"raw_events_0\") t", "" ], @@ -305,7 +305,8 @@ " t.amount,", " t.status,", " t.created_at,", - " (t.amount + 0 + 1) AS adjust_0_amount", + " (t.amount + 0 + 1) AS adjust_0_amount,", + " 'Zürich – depot' AS site_label", "FROM __source(\"raw_events_0\") t", "" ], @@ -316,7 +317,8 @@ " t.amount,", " t.status,", " t.created_at,", - " (t.amount + 0 + 1) AS adjust_0_amount", + " (t.amount + 0 + 1) AS adjust_0_amount,", + " 'Zürich – depot' AS site_label", "FROM __source__raw_events_0 t),", "__ref__labelled_stg_support_1 AS (SELECT id, LOWER(TRIM(status)) AS status,", " ci_checks.tidy_status(status) AS tidied", @@ -336,7 +338,8 @@ " t.amount,", " t.status,", " t.created_at,", - " t.amount * 2.4700 AS threshold_0_amount", + " t.amount * 2.4700 AS threshold_0_amount,", + " 'Zürich – depot' AS site_label", "FROM __source__raw_events_0 t),", "__actual__stg_support_0 AS (SELECT * FROM __ref__stg_support_0),", "__expected__stg_support_0 AS (SELECT 1 AS id, 'placed' AS status)", @@ -352,7 +355,8 @@ " t.amount,", " t.status,", " t.created_at,", - " t.amount * 2.4700 AS threshold_0_amount", + " t.amount * 2.4700 AS threshold_0_amount,", + " 'Zürich – depot' AS site_label", "FROM __source__raw_events_0 t),", "__actual__stg_support_0 AS (SELECT * FROM __ref__stg_support_0),", "__expected__stg_support_0 AS (SELECT 1 AS id)", @@ -368,7 +372,8 @@ " t.amount,", " t.status,", " t.created_at,", - " t.amount * 2.4700 AS threshold_0_amount", + " t.amount * 2.4700 AS threshold_0_amount,", + " 'Zürich – depot' AS site_label", "FROM __source__raw_events_0 t),", "__actual__stg_support_0 AS (SELECT * FROM __ref__stg_support_0),", "__expected__stg_support_0 AS (SELECT 1 AS id)", @@ -1157,18 +1162,7 @@ "incremental_strategy": null, "merge_exclude_columns": null, "persist_docs": {}, - "post-hook": [ - { - "sql": "SELECT 'ci_checks.billing_summary_0' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "transaction": true, - "index": 0 - }, - { - "sql": "SELECT 'ci_checks.billing_summary_0' AS refreshed", - "transaction": true, - "index": 1 - } - ], + "post-hook": [], "pre-hook": [], "quoting": {}, "column_types": {}, @@ -1200,30 +1194,7 @@ "tags": [] } }, - "meta": { - "sqlbuild": { - "lifecycle_hooks": { - "post_hooks": [ - { - "type": "sql", - "statement": "SELECT 'ci_checks.billing_summary_0' AS refreshed_relation, 'Ελληνικά orders' AS refresh_label", - "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", - "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", - "kwargs": { - "relation": "@@CTX:destination.qualified", - "label": "Ελληνικά orders" - }, - "description": "Record a refresh for one relation" - }, - { - "type": "sql", - "statement": "SELECT 'ci_checks.billing_summary_0' AS refreshed" - } - ] - } - } - }, + "meta": {}, "group": null, "docs": { "show": true, @@ -1296,7 +1267,17 @@ "staging" ], "description": "Staged billing events 0", - "columns": {}, + "columns": { + "id": { + "name": "id", + "description": "", + "meta": {}, + "data_type": null, + "constraints": [], + "quote": null, + "tags": [] + } + }, "meta": {}, "group": null, "docs": { @@ -2451,7 +2432,7 @@ "type": "sql", "statement": "SELECT 'ci_checks.support_summary_0' AS refreshed_relation, 'café ☕ counter' AS refresh_label", "name": "record_refresh", - "relative_path": "hooks/sql/record_refresh.sql", + "relative_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "definition_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "kwargs": { "relation": "@@CTX:destination.qualified", @@ -2613,17 +2594,7 @@ "staging" ], "description": "Staged support events 1", - "columns": { - "id": { - "name": "id", - "description": "", - "meta": {}, - "data_type": null, - "constraints": [], - "quote": null, - "tags": [] - } - }, + "columns": {}, "meta": {}, "group": null, "docs": { @@ -3072,8 +3043,8 @@ "name": "record_refresh", "resource_type": "macro", "package_name": "generated_9__sqlbuild_hooks", - "path": "hooks/sql/record_refresh.sql", - "original_file_path": "hooks/sql/record_refresh.sql", + "path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", + "original_file_path": "models/support/marts/_sqlbuild/_hooks/sql/record_refresh.sql", "unique_id": "macro.generated_9__sqlbuild_hooks.record_refresh", "macro_sql": "SELECT @'relation' AS refreshed_relation, @'label' AS refresh_label", "depends_on": { diff --git a/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py b/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py index 7a16ef2e73..cb84d63a02 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py @@ -1595,3 +1595,80 @@ class DynamicRefreshWarehouseTestCase: description: str argv: tuple[str, ...] expected_refresh_warehouses: tuple[str, ...] + + +@dataclass(frozen=True) +class ExpansionBoundaryTestCase: + """A project whose model splices text beside its own, and the rows a build gives.""" + + description: str + model_sql: str + expected_rows: tuple[tuple[object, ...], ...] + model_config: str = "" + files: dict[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class CursorBoundaryTestCase: + description: str + start: str + expected_sql: str + + +@dataclass(frozen=True) +class IgnoredCancelTestCase: + description: str + sent_signal: signal.Signals + expected_exit_code: int + expected_line: str + expected_within_seconds: float + adapter: str = "duckdb" + + +@dataclass(frozen=True) +class InterruptedCommandTestCase: + description: str + command: tuple[str, ...] + # What the adapter's connect runs before it opens the connection. + connect: str + # What the terminal shows once the command waits. + waiting: str + expected_line: str + settle_seconds: float = 0.3 + presses: int = 1 + files: dict[str, str] = field(default_factory=dict) + # The forced exit's own worst case is its 0.6 s grace plus two 1 s joins. + expected_within_seconds: float = 3.0 + + +@dataclass(frozen=True) +class HungSetupCancelTestCase: + description: str + sent_signal: signal.Signals + expected_exit_code: int + expected_within_seconds: float + + +@dataclass(frozen=True) +class SinkAbandonedStepTestCase: + description: str + parameters: str + step_body: str + started_markers: tuple[str, ...] + started_lines: tuple[str, ...] + sent_signal: signal.Signals + expected_exit_code: int + + +@dataclass(frozen=True) +class SinkNormalRunTestCase: + description: str + expected_last_line: str + + +@dataclass(frozen=True) +class MidSubmitCancelTestCase: + description: str + sent_signal: signal.Signals + expected_exit_code: int + expected_notice: str diff --git a/tests/integration/src/sqlbuild/cli/commands/main/helpers.py b/tests/integration/src/sqlbuild/cli/commands/main/helpers.py index 172f4bc8e6..379a373b66 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/helpers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/helpers.py @@ -1,7 +1,9 @@ from __future__ import annotations +import fcntl import json import os +import pty import re import shutil import signal @@ -9,12 +11,15 @@ import subprocess import sys import tempfile +import termios import time from collections import defaultdict from collections.abc import Callable, Iterable +from contextlib import suppress from datetime import datetime, timedelta from itertools import accumulate, chain, compress, takewhile from pathlib import Path +from threading import Thread from types import ModuleType from typing import Any, cast @@ -37,8 +42,10 @@ from sqlbuild.adapter.contract.types import RetentionChangePhase from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter from tests.integration.src.sqlbuild.cli.commands.main._test_types import ( + ExpansionBoundaryTestCase, RepeatedJsonParseTestCase, ) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files from tests.unit.src.sqlbuild.rule_engine._helpers.run.helpers import rebuild_identity STAGE_CAPTURE_SUFFIX: str = ".json" @@ -658,6 +665,24 @@ def compile_duckdb_query( return exit_code, tuple(item["code"] for item in diagnostics) +def write_boundary_project(*, project_dir: Path, test_case: ExpansionBoundaryTestCase) -> None: + """Write one case's model and the declarations it expands, on a DuckDB file.""" + + files: dict[str, str] = { + "sqlbuild_project.toml": ( + 'name = "orders"\nadapter = "duckdb"\n[connection]\ndatabase = "orders.duckdb"\n' + '[vars]\nnegative = "-1"\n' + ), + "models/orders.sql": ( + f"MODEL (description 'Orders.', materialized table{test_case.model_config});\n" + f"{test_case.model_sql}\n" + ), + } | test_case.files + for path, text in files.items(): + (project_dir / path).parent.mkdir(parents=True, exist_ok=True) + _ = (project_dir / path).write_text(text) + + def write_expression_source_project( *, project_dir: Path, source_expression: str, model_sql: str ) -> None: @@ -1345,6 +1370,117 @@ def signalled_scenario_run( return process.returncode, started + stdout + stderr, time.monotonic() - sent +def write_prompting_project(project_dir: Path, *, connect: str, files: dict[str, str]) -> Path: + """A project whose adapter runs `connect` before it opens its connection.""" + + adapter: str = ( + "import getpass\n" + "from concurrent.futures import ThreadPoolExecutor\n\n" + "from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter\n\n\n" + "class DuckDbSignInAdapter(DuckDbAdapter):\n" + ' adapter_name = "duckdb_sign_in"\n\n' + " def connect(self, config):\n" + f"{connect}" + " return super().connect(config)\n" + ) + project: dict[str, str] = { + "sqlbuild_project.toml": ( + 'name = "orders"\nadapter = "duckdb_sign_in"\ndefault_target = "development"\n' + '[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n' + "[rules]\nselect = []\n" + ), + "adapters/duckdb_sign_in.py": adapter, + "models/customers.sql": ( + "MODEL (description 'Customers.', materialized table);\nSELECT 1 AS customer_id\n" + ), + } | files + for path, text in project.items(): + (project_dir / path).parent.mkdir(parents=True, exist_ok=True) + _ = (project_dir / path).write_text(text, encoding="utf-8") + return project_dir + + +def interrupt_on_terminal( + project_dir: Path, *, command: tuple[str, ...], waiting: str, settle: float, presses: int +) -> tuple[int, float, str, bool]: + """`sqb` on its own terminal, sent SIGINT once it waits: its exit code, the seconds it then + took, what it showed and whether the terminal still echoes.""" + + terminal, attached = pty.openpty() + environment: dict[str, str] = {**os.environ, "TERM": "xterm"} + _ = environment.pop("CI", None) + process: subprocess.Popen[bytes] = subprocess.Popen( + [str(Path(sys.executable).with_name("sqb")), *command], + cwd=project_dir, + stdin=attached, + stdout=attached, + stderr=attached, + env=environment, + start_new_session=True, + preexec_fn=_interruptible_terminal, + ) + written: list[bytes] = [] + reader: Thread = Thread(target=_read_terminal, args=(terminal, written), daemon=True) + reader.start() + try: + deadline: float = time.monotonic() + 60 + while waiting.encode() not in b"".join(written): + assert process.poll() is None, b"".join(written).decode(errors="replace") + assert time.monotonic() < deadline, b"".join(written).decode(errors="replace") + time.sleep(0.02) + time.sleep(settle) + sent: float = time.monotonic() + for _ in range(presses): + os.killpg(process.pid, signal.SIGINT) + time.sleep(0.05) + exit_code: int = process.wait(timeout=15) + seconds: float = time.monotonic() - sent + echoes: bool = bool(termios.tcgetattr(attached)[3] & termios.ECHO) + finally: + process.kill() + _ = process.wait(timeout=5) + os.close(attached) + reader.join(timeout=5) + os.close(terminal) + return exit_code, seconds, b"".join(written).decode(errors="replace"), echoes + + +def recorded_ending(project_dir: Path) -> list[object]: + """The status, exit code and signal Recall has for the project's last command.""" + + shown: subprocess.CompletedProcess[str] = subprocess.run( + [ + str(Path(sys.executable).with_name("sqb")), + "recall", + "query", + "SELECT status, exit_code, signal_number FROM invocations " + "ORDER BY invocation_started_at DESC LIMIT 1", + "--format", + "json", + ], + cwd=project_dir, + capture_output=True, + text=True, + check=True, + ) + rows: list[list[object]] = json.loads(shown.stdout)["rows"] + return rows[0] + + +def _interruptible_terminal() -> None: + """In the child: default Ctrl-C handling, and the terminal on stdin as the session's own.""" + + _default_interrupt_handling() + _ = fcntl.ioctl(0, termios.TIOCSCTTY, 0) + + +def _read_terminal(terminal: int, written: list[bytes]) -> None: + with suppress(OSError): + while chunk := os.read(terminal, 65536): + written.append(chunk) + + def _default_interrupt_handling() -> None: """Give the spawned command default Ctrl-C handling even when its parent ignores SIGINT.""" @@ -1856,3 +1992,101 @@ def dynamic_refresh_warehouses(executed_sql: list[str]) -> tuple[str, ...]: return tuple( re.findall(r"CREATE OR REPLACE DYNAMIC TABLE .*?WAREHOUSE = (\S+)", statements, re.S) ) + + +_SINK_STEPS: str = """\ +import time +from pathlib import Path + +from providers.gateway import GatewayProvider +from providers.journal import JournalProvider +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) + + +@discover +def fulfilment_plan() -> Discovered: + \"\"\"Two steps at once.\"\"\" + return Discovered(items=[Item(id="pack"), Item(id="pick")], max_parallel=2) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext, journal_provider: JournalProvider, {parameters}) -> None: + \"\"\"Run one step.\"\"\" + {body} +""" +_SINK_JOURNAL: str = """\ +from pathlib import Path + +from sqlbuild.providers import Provider + + +class JournalProvider(Provider): + \"\"\"Appends lines to a journal.\"\"\" + + def write(self, line: str) -> None: + with Path({directory!r}, "journal.txt").open("a") as journal: + journal.write(line + "\\n") + + def teardown(self) -> None: + self.write("torn down") +""" +_SINK_GATEWAY: str = """\ +import time +from pathlib import Path + +from sqlbuild.providers import Provider + + +class GatewayProvider(Provider): + \"\"\"A gateway whose first connection never completes.\"\"\" + + def setup(self, ctx) -> None: + Path({directory!r}, "setup-started").touch() + time.sleep(3600) +""" +_SINK_FUNCTION: str = """\ +from providers.journal import JournalProvider +from sqlbuild.sinks import LifecycleEvent, lifecycle_event_sink + + +@lifecycle_event_sink +def journal_events(event: LifecycleEvent, journal_provider: JournalProvider) -> None: + journal_provider.write(f"event {event.event_type}") +""" +_SINK_PROJECT_TOML: str = ( + 'name = "fulfilment"\nadapter = "duckdb"\ndefault_target = "development"\n\n' + '[connection]\ndatabase = "warehouse.duckdb"\n\n[targets.development]\nschema = "main"\n' +) + + +def sink_project(tmp_path: Path, *, parameters: str, body: str) -> Path: + """A project whose steps and lifecycle sink share a journal provider.""" + + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": _SINK_PROJECT_TOML, + "python/steps.py": _SINK_STEPS.format( + directory=str(tmp_path), parameters=parameters, body=body + ), + "providers/journal.py": _SINK_JOURNAL.format(directory=str(tmp_path)), + "providers/gateway.py": _SINK_GATEWAY.format(directory=str(tmp_path)), + "sinks/journal.py": _SINK_FUNCTION, + }, + ) + return project + + +def build_arguments(project: Path) -> list[str]: + """`sqb build --discover` of `project`.""" + + return [str(Path(sys.executable).with_name("sqb")), "--no-color"] + [ + "--project-dir", + str(project), + "build", + "--discover", + ] diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_command_interruption.py b/tests/integration/src/sqlbuild/cli/commands/main/test_command_interruption.py new file mode 100644 index 0000000000..e38dee4e50 --- /dev/null +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_command_interruption.py @@ -0,0 +1,178 @@ +"""Ctrl+C stops a command at any point, run by the real CLI on a pseudo-terminal.""" + +import sys +from pathlib import Path + +import pytest + +from tests.integration.src.sqlbuild.cli.commands.main._test_types import ( + InterruptedCommandTestCase, +) +from tests.integration.src.sqlbuild.cli.commands.main.helpers import ( + interrupt_on_terminal, + recorded_ending, + write_prompting_project, +) + +_LINE: str = "error: interrupted (Ctrl+C)" +_INPUT: str = ' input("Sign-in code: ")\n' +_SWALLOWED: str = ( + " try:\n" + ' input("Sign-in code: ")\n' + " except BaseException as error:\n" + ' raise RuntimeError("sign-in failed") from error\n' +) +_RETRIED: str = ( + " try:\n" + ' input("Sign-in code: ")\n' + " except KeyboardInterrupt:\n" + ' input("Sign-in code again: ")\n' +) +_HIDDEN: str = ( + " try:\n" + ' input("Sign-in code: ")\n' + " except KeyboardInterrupt:\n" + ' getpass.getpass("Password: ")\n' +) +_THREADED: str = ( + " with ThreadPoolExecutor(1) as pool:\n" + ' pool.submit(input, "Sign-in code: ").result()\n' +) +_ENDLESS: str = ( + "SELECT count(*) AS amount FROM range(100000000) a, range(100000000) b " + "WHERE (a.range * b.range) % 7 = 1" +) +_READING_ASSET: str = ( + "from concurrent.futures import ThreadPoolExecutor\n\n" + "from sqlbuild.assets import asset\n" + "from sqlbuild.refs import model\n\n\n" + '@asset(depends_on=model("customers"))\n' + "def reader(ctx):\n" + ' """Read a line on another thread."""\n' + " with ThreadPoolExecutor(1) as pool:\n" + ' pool.submit(input, "Value: ").result()\n' +) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pseudo-terminal contract") +@pytest.mark.parametrize( + "test_case", + [ + InterruptedCommandTestCase( + "debug at a sign-in prompt", ("debug",), _INPUT, "Sign-in code:", _LINE + ), + InterruptedCommandTestCase( + "build at a sign-in prompt", ("build",), _INPUT, "Sign-in code:", _LINE + ), + InterruptedCommandTestCase( + "sqb dev at a sign-in prompt", + ("dev", "--port", "0", "--no-scheduler"), + _INPUT, + "Sign-in code:", + "sqb dev stopped (interrupted)", + ), + InterruptedCommandTestCase( + "a driver that turns the interrupt into its own error", + ("debug",), + _SWALLOWED, + "Sign-in code:", + _LINE, + ), + InterruptedCommandTestCase( + "a driver that asks again", ("debug",), _RETRIED, "Sign-in code:", _LINE + ), + InterruptedCommandTestCase( + "a driver that asks again without echo", ("debug",), _HIDDEN, "Sign-in code:", _LINE + ), + InterruptedCommandTestCase( + "a prompt read on another thread", ("build",), _THREADED, "Sign-in code:", _LINE + ), + InterruptedCommandTestCase( + "a running build statement is cancelled", + ("build", "--select", "orders"), + "", + "Warehouse connected", + _LINE, + settle_seconds=1.5, + files={ + "models/orders.sql": ( + f"MODEL (description 'Orders.', materialized table);\n{_ENDLESS}\n" + ) + }, + expected_within_seconds=5.0, + ), + InterruptedCommandTestCase( + "a running query is cancelled", + ("query", _ENDLESS), + "", + "Running query", + _LINE, + settle_seconds=1.0, + expected_within_seconds=5.0, + ), + InterruptedCommandTestCase( + "a second press ends a read that outlives the statements before it", + ("build",), + "", + "Value: ", + _LINE, + presses=2, + files={"python/assets/reader.py": _READING_ASSET}, + expected_within_seconds=5.0, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_waiting_command_when_interrupted_then_it_exits_130_promptly_and_says_so( + test_case: InterruptedCommandTestCase, tmp_path: Path +) -> None: + project: Path = write_prompting_project( + tmp_path / "orders", connect=test_case.connect, files=test_case.files + ) + + exit_code, seconds, shown, echoes = interrupt_on_terminal( + project, + command=test_case.command, + waiting=test_case.waiting, + settle=test_case.settle_seconds, + presses=test_case.presses, + ) + + assert exit_code == 130, shown + assert seconds < test_case.expected_within_seconds, shown + assert test_case.expected_line in shown, shown + assert "Traceback" not in shown, shown + assert echoes, shown + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX pseudo-terminal contract") +@pytest.mark.parametrize( + "test_case", + [ + InterruptedCommandTestCase( + "an interrupt the driver turned into its own error", + ("debug",), + _SWALLOWED, + "Sign-in code:", + _LINE, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_swallowed_interrupt_when_the_command_ends_then_recall_records_it_cancelled( + test_case: InterruptedCommandTestCase, tmp_path: Path +) -> None: + project: Path = write_prompting_project( + tmp_path / "orders", connect=test_case.connect, files=test_case.files + ) + + _, _, shown, _ = interrupt_on_terminal( + project, + command=test_case.command, + waiting=test_case.waiting, + settle=test_case.settle_seconds, + presses=test_case.presses, + ) + + assert test_case.expected_line in shown, shown + assert recorded_ending(project) == ["cancelled", 130, 2], shown diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_command_termination.py b/tests/integration/src/sqlbuild/cli/commands/main/test_command_termination.py index 7157e48cfc..353417f65a 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_command_termination.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_command_termination.py @@ -24,8 +24,8 @@ SignalledScenarioTestCase( description="Ctrl+C cancels the running statement", sent_signal=signal.SIGINT, - expected_exit_code=-signal.SIGINT, - expected_last_line="KeyboardInterrupt", + expected_exit_code=130, + expected_last_line="error: interrupted (Ctrl+C)", ), SignalledScenarioTestCase( description="SIGTERM cancels the running statement the same way", diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_expansion_boundaries.py b/tests/integration/src/sqlbuild/cli/commands/main/test_expansion_boundaries.py new file mode 100644 index 0000000000..6b0371161f --- /dev/null +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_expansion_boundaries.py @@ -0,0 +1,221 @@ +"""An expansion never opens or extends a comment, built by the real CLI on DuckDB.""" + +from pathlib import Path + +import pytest + +from sqlbuild._native import ( + MICROBATCH_END_SENTINEL, + MICROBATCH_START_SENTINEL, + replace_cursor_markers, + resolve_cursor_intrinsics, +) +from sqlbuild._native import run_cli as main +from tests.integration.src.sqlbuild.cli.commands.main._test_types import ( + CursorBoundaryTestCase, + ExpansionBoundaryTestCase, +) +from tests.integration.src.sqlbuild.cli.commands.main.helpers import ( + query_duckdb_rows, + write_boundary_project, +) + +_NEG: dict[str, str] = { + "models/_macros/python/neg.py": 'def neg():\n """Return minus one."""\n return "-1"\n' +} +_NOTED: dict[str, str] = { + "models/_macros/python/noted.py": ( + 'def noted():\n """Return one with a note."""\n return "1 -- one"\n' + ) +} + + +@pytest.mark.parametrize( + "test_case", + [ + ExpansionBoundaryTestCase( + "a negative Python macro after a minus", + "SELECT -@py.neg() AS x, 7 AS y", + ((1, 7),), + files=_NEG, + ), + ExpansionBoundaryTestCase( + "a Python macro ending in a line comment", + "SELECT @py.noted() AS x, 7 AS y", + ((1, 7),), + files=_NOTED, + ), + ExpansionBoundaryTestCase( + "an empty Python macro between two minuses", + "SELECT 5 -@py.blank()-2 AS x, 7 AS y", + ((7, 7),), + files={ + "models/_macros/python/blank.py": ( + 'def blank():\n """Return nothing."""\n return ""\n' + ) + }, + ), + ExpansionBoundaryTestCase( + "a deliberate join", + "SELECT 4 AS @py.stem()_count", + ((4,),), + files={ + "models/_macros/python/stem.py": ( + 'def stem():\n """Return a stem."""\n return "orders"\n' + ) + }, + ), + ExpansionBoundaryTestCase( + "a negative constant", + 'SELECT -@const("minus_one") AS x, 7 AS y', + ((1, 7),), + files={"models/_constants/minus_one.sql": "CONSTANT (name minus_one, value -1);\n"}, + ), + ExpansionBoundaryTestCase( + "a negative enum member", + 'SELECT -@enum("sign").DOWN AS x, 7 AS y', + ((1, 7),), + files={"models/_enums/sign.sql": "ENUM (name sign, members (DOWN -1, UP 1));\n"}, + ), + ExpansionBoundaryTestCase( + "a negative variable", + "SELECT -@@negative AS x, 7 AS y", + ((1, 7),), + ), + ExpansionBoundaryTestCase( + "a negative SQL macro", + "SELECT -@sql.negative_one() AS x, 7 AS y", + ((1, 7),), + files={ + "models/_macros/sql/negative_one.sql": ( + 'MACRO (\n description "Minus one",\n);\n\n-1\n' + ) + }, + ), + ExpansionBoundaryTestCase( + "a negative audit argument", + "SELECT 1 AS x, 7 AS y", + ((1, 7),), + model_config=", audits [x_is (value -1)]", + files={ + "audits/generic/x_is.sql": ( + "AUDIT ();\nSELECT * FROM @relation WHERE x <> -@value AND y > 0\n" + ) + }, + ), + ExpansionBoundaryTestCase( + "a negative hook argument", + "SELECT 1 AS x, 7 AS y", + ((1, 7),), + model_config=', post_hooks [sql("note_value", value: -1)]', + files={ + "hooks/sql/note_value.sql": ( + 'HOOK (description "Read a value");\nSELECT -@value AS x, 7 AS y\n' + ) + }, + ), + ExpansionBoundaryTestCase( + "a negative test parameter", + 'SELECT x, 7 AS y FROM __ref("amounts")', + ((1, 7),), + files={ + "models/amounts.sql": ( + "MODEL (description 'Amounts.', materialized table);\nSELECT 1 AS x\n" + ), + "tests/unit/test_orders.sql": ( + "TEST (parameters (value INTEGER), cases (single (value -1)));\n" + "WITH __ref__amounts AS (SELECT 1 AS x),\n" + "__expected__orders AS (\n" + ' SELECT -@param("value") AS x, 7 AS y\n' + ")\nSELECT 1\n" + ), + }, + ), + ExpansionBoundaryTestCase( + "a source expression ending in a line comment", + 'SELECT x, 7 AS y FROM __source("amounts") WHERE x = 2', + ((2, 7),), + files={ + "sources/amounts.yml": ( + "sources:\n - name: amounts\n description: Amounts.\n" + ' expression: "(SELECT * FROM (VALUES (1), (2)) AS v(x)) -- amounts"\n' + ) + }, + ), + ExpansionBoundaryTestCase( + "a SQL macro argument ending in a line comment", + "SELECT @sql.same(2 + 3 -- five\n) AS x, 7 AS y", + ((5, 7),), + files={ + "models/_macros/sql/same.sql": ( + 'MACRO (\n description "The amount",\n arguments (amount INTEGER),\n);\n\n' + "@amount\n" + ) + }, + ), + ], + ids=lambda case: case.description, +) +def test_given_an_expansion_beside_its_neighbour_when_building_then_neither_opens_a_comment( + test_case: ExpansionBoundaryTestCase, tmp_path: Path +) -> None: + write_boundary_project(project_dir=tmp_path, test_case=test_case) + assert main(["--project-dir", str(tmp_path), "build"]) == 0, test_case.description + assert ( + query_duckdb_rows(db_path=tmp_path / "orders.duckdb", sql="SELECT * FROM main.orders") + == test_case.expected_rows + ) + + +@pytest.mark.parametrize( + "test_case", + [ + ExpansionBoundaryTestCase( + "a space between a minus and a negative", + "select - @py.neg() as x, 7 as y", + ((1, 7),), + files=_NEG, + ), + ExpansionBoundaryTestCase( + "a newline after a macro ending in a comment", + "select @py.noted()\n as x, 7 as y", + ((1, 7),), + files=_NOTED, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_formatted_expansion_site_when_building_then_results_do_not_change( + test_case: ExpansionBoundaryTestCase, tmp_path: Path +) -> None: + write_boundary_project(project_dir=tmp_path, test_case=test_case) + built: list[tuple[tuple[object, ...], ...]] = [] + for command in (("build",), ("format",), ("build", "--full-refresh")): + assert main(["--project-dir", str(tmp_path), *command]) == 0, command + built.append( + query_duckdb_rows(db_path=tmp_path / "orders.duckdb", sql="SELECT * FROM main.orders") + ) + assert built == [test_case.expected_rows] * 3 + + +@pytest.mark.parametrize( + "test_case", + [ + CursorBoundaryTestCase("a negative start", "-5", "SELECT x- -5, 'a-5', x-9"), + CursorBoundaryTestCase("a positive start", "5", "SELECT x-5, 'a5', x-9"), + ], + ids=lambda case: case.description, +) +def test_given_a_cursor_bound_after_a_minus_when_substituted_then_it_opens_no_comment( + test_case: CursorBoundaryTestCase, +) -> None: + intrinsic: str = "SELECT x-__cursor_start(), 'a{start}', x-__cursor_end()" + resolved, _ = resolve_cursor_intrinsics( + sql=intrinsic.format(start=test_case.start), start_sql=test_case.start, end_sql="9" + ) + marked: str = ( + f"SELECT x-{MICROBATCH_START_SENTINEL}, " + f"'a{MICROBATCH_START_SENTINEL}', x-{MICROBATCH_END_SENTINEL}" + ) + replaced: str = replace_cursor_markers(sql=marked, start_sql=test_case.start, end_sql="9") + assert (resolved, replaced) == (test_case.expected_sql, test_case.expected_sql) diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_ignored_cancel.py b/tests/integration/src/sqlbuild/cli/commands/main/test_ignored_cancel.py new file mode 100644 index 0000000000..8b9e955965 --- /dev/null +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_ignored_cancel.py @@ -0,0 +1,311 @@ +"""Real CLI coverage for a cancel of discovered steps that ignore it.""" + +import os +import signal +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +from tests.integration.src.sqlbuild.cli.commands.main._test_types import ( + HungSetupCancelTestCase, + IgnoredCancelTestCase, + MidSubmitCancelTestCase, +) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files + +_STEPS: str = '''\ +import time +from pathlib import Path + +from providers.marker import MarkerProvider +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) + + +@discover +def fulfilment_plan() -> Discovered: + """Two steps at once.""" + return Discovered(items=[Item(id="pack"), Item(id="pick")], max_parallel=2) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext, marker_provider: MarkerProvider) -> None: + """Ignore any cancel.""" + (DIRECTORY / f"{{ctx.discovered.item}}.running").touch() + time.sleep(120) +''' +# One Ctrl+C may force an exit only while no statement has ever run, so this adapter records none. +_UNRECORDED_ADAPTER: str = '''\ +from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter + + +class DuckDbUnrecordedAdapter(DuckDbAdapter): + """Run statements without recording them as running.""" + + adapter_name = "duckdb_unrecorded" + + def execute(self, *, connection, sql): + return self._execute(connection=connection, sql=sql) +''' +_PROVIDER: str = '''\ +from pathlib import Path + +from sqlbuild.providers import Provider + + +class MarkerProvider(Provider): + """Say when it was torn down.""" + + def teardown(self) -> None: + Path({directory!r}, "torn-down").touch() +''' + +_HUNG_STEPS: str = """\ +from providers.gateway import GatewayProvider +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + + +@discover +def fulfilment_plan() -> Discovered: + \"\"\"Two steps at once.\"\"\" + return Discovered(items=[Item(id="pack"), Item(id="pick")], max_parallel=2) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext, gateway_provider: GatewayProvider) -> None: + \"\"\"Use the gateway.\"\"\" +""" +_HUNG_PROVIDER: str = """\ +import time +from pathlib import Path + +from sqlbuild.providers import Provider + + +class GatewayProvider(Provider): + \"\"\"A gateway whose first connection never completes.\"\"\" + + def setup(self, ctx) -> None: + Path({directory!r}, "setup-started").touch() + time.sleep(3600) + + def teardown(self) -> None: + Path({directory!r}, "torn-down").touch() +""" + +_BOTH_STARTED: tuple[str, ...] = ("fulfil[pack] START", "fulfil[pick] START") +_SLOW_SUBMIT: str = """\\ +import time +from concurrent.futures import ThreadPoolExecutor + +ADJUST = ThreadPoolExecutor._adjust_thread_count + + +def slow_second_start(self) -> None: + \"\"\"Keep the caller inside `submit` for a while once a second thread has started.\"\"\" + ADJUST(self) + if len(self._threads) > 1: + time.sleep(3) + + +ThreadPoolExecutor._adjust_thread_count = slow_second_start +""" + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signals") +@pytest.mark.parametrize( + "test_case", + [ + IgnoredCancelTestCase( + description="SIGTERM exits after the 5 seconds without provider teardown", + sent_signal=signal.SIGTERM, + expected_exit_code=143, + expected_line="error: terminated by SIGTERM", + expected_within_seconds=20, + ), + IgnoredCancelTestCase( + description="Ctrl+C exits after the 5 seconds without provider teardown", + sent_signal=signal.SIGINT, + expected_exit_code=130, + expected_line="error: interrupted (Ctrl+C)", + expected_within_seconds=20, + ), + IgnoredCancelTestCase( + description="one Ctrl+C waits the 5 seconds though no statement has ever run", + sent_signal=signal.SIGINT, + expected_exit_code=130, + expected_line="error: interrupted (Ctrl+C)", + expected_within_seconds=20, + adapter="duckdb_unrecorded", + ), + ], + ids=lambda case: case.description, +) +def test_given_steps_ignoring_cancel_when_signalled_then_the_command_exits_without_teardown( + test_case: IgnoredCancelTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": f'name = "fulfilment"\nadapter = "{test_case.adapter}"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "python/steps.py": _STEPS.format(directory=str(tmp_path)), + "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + "adapters/duckdb_unrecorded.py": _UNRECORDED_ADAPTER, + }, + ) + log: Path = tmp_path / "build.log" + with log.open("wb") as output: + process: subprocess.Popen[bytes] = subprocess.Popen( + [str(Path(sys.executable).with_name("sqb")), "--no-color"] + + ["--project-dir", str(project), "build", "--discover"], + stdout=output, + stderr=subprocess.STDOUT, + env=os.environ | {"HOME": str(tmp_path)}, + ) + try: + deadline: float = time.monotonic() + 60 + while len(list(tmp_path.glob("*.running"))) < 2: + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, log.read_text() + time.sleep(0.05) + process.send_signal(test_case.sent_signal) + exit_code: int = process.wait(timeout=test_case.expected_within_seconds) + finally: + process.kill() + _ = process.wait(timeout=5) + + assert exit_code == test_case.expected_exit_code, log.read_text() + assert test_case.expected_line in log.read_text() + assert "Stopped waiting for fulfil[pack], fulfil[pick] after 5 seconds" in log.read_text() + assert not (tmp_path / "torn-down").exists() + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signals") +@pytest.mark.parametrize( + "test_case", + [ + HungSetupCancelTestCase( + description="SIGTERM exits after the 5 seconds", + sent_signal=signal.SIGTERM, + expected_exit_code=143, + expected_within_seconds=20, + ), + HungSetupCancelTestCase( + description="Ctrl+C exits after the 5 seconds", + sent_signal=signal.SIGINT, + expected_exit_code=130, + expected_within_seconds=20, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_step_in_a_provider_setup_that_never_returns_when_cancelled_then_the_command_exits( + test_case: HungSetupCancelTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "python/steps.py": _HUNG_STEPS, + "providers/gateway.py": _HUNG_PROVIDER.format(directory=str(tmp_path)), + }, + ) + log: Path = tmp_path / "build.log" + with log.open("wb") as output: + process: subprocess.Popen[bytes] = subprocess.Popen( + [str(Path(sys.executable).with_name("sqb")), "--no-color"] + + ["--project-dir", str(project), "build", "--discover"], + stdout=output, + stderr=subprocess.STDOUT, + env=os.environ | {"HOME": str(tmp_path)}, + ) + try: + deadline: float = time.monotonic() + 60 + while not ( + (tmp_path / "setup-started").exists() + and all(line in log.read_text() for line in _BOTH_STARTED) + ): + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, log.read_text() + time.sleep(0.05) + process.send_signal(test_case.sent_signal) + exit_code: int = process.wait(timeout=test_case.expected_within_seconds) + finally: + process.kill() + _ = process.wait(timeout=5) + + assert exit_code == test_case.expected_exit_code, log.read_text() + assert "Stopped waiting for fulfil[pack], fulfil[pick] after 5 seconds" in log.read_text() + assert not (tmp_path / "torn-down").exists() + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signals") +@pytest.mark.parametrize( + "test_case", + [ + MidSubmitCancelTestCase( + description="SIGTERM while the second step is being submitted", + sent_signal=signal.SIGTERM, + expected_exit_code=143, + expected_notice="Stopped waiting for fulfil[pack], fulfil[pick] after 5 seconds", + ), + MidSubmitCancelTestCase( + description="Ctrl+C while the second step is being submitted", + sent_signal=signal.SIGINT, + expected_exit_code=130, + expected_notice="Stopped waiting for fulfil[pack], fulfil[pick] after 5 seconds", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_cancel_inside_a_steps_submit_when_steps_ignore_it_then_both_are_abandoned( + test_case: MidSubmitCancelTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "python/steps.py": _STEPS.format(directory=str(tmp_path)), + "python/slow_submit.py": _SLOW_SUBMIT, + "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + }, + ) + log: Path = tmp_path / "build.log" + with log.open("wb") as output: + process: subprocess.Popen[bytes] = subprocess.Popen( + [str(Path(sys.executable).with_name("sqb")), "--no-color"] + + ["--project-dir", str(project), "build", "--discover"], + stdout=output, + stderr=subprocess.STDOUT, + env=os.environ | {"HOME": str(tmp_path)}, + ) + try: + deadline: float = time.monotonic() + 60 + while len(list(tmp_path.glob("*.running"))) < 2: + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, log.read_text() + time.sleep(0.05) + process.send_signal(test_case.sent_signal) + exit_code: int = process.wait(timeout=20) + finally: + process.kill() + _ = process.wait(timeout=5) + + assert exit_code == test_case.expected_exit_code, log.read_text() + assert test_case.expected_notice in log.read_text() + assert not (tmp_path / "torn-down").exists() diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py b/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py index 22b9c2b2db..c6a4ec1216 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_load_command.py @@ -626,7 +626,7 @@ def raw_orders(ctx): @loader def raw_orders(ctx): '''Test loader raw_orders.''' - ctx.log("loading raw orders") + ctx.log.info("loading raw orders") return [ {"order_id": 1, "status": "placed"}, {"order_id": 2, "status": "shipped"}, @@ -1904,7 +1904,7 @@ def test_given_build_skips_loader_when_manifest_is_written_then_marks_source_aut @loader def raw_orders(ctx): '''Test loader raw_orders.''' - ctx.log("loading raw orders") + ctx.log.info("loading raw orders") return [ {"order_id": 1, "status": "placed"}, {"order_id": 2, "status": "shipped"}, @@ -2124,7 +2124,7 @@ def test_given_source_loader_when_running_load_then_writes_source_table( @loader def raw_orders(ctx): '''Test loader raw_orders.''' - ctx.log("loading raw orders") + ctx.log.info("loading raw orders") return [ {"order_id": 1, "status": "placed"}, {"order_id": 2, "status": "shipped"}, diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py b/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py index 1b981a7540..f01a5e50df 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py @@ -17,7 +17,7 @@ from sqlbuild._native import run_cli as main from sqlbuild.adapter.contract.classes.runs_table import RunsTableMixin -from sqlbuild.runtime.execution_limits.main._cancel_running_statements import ( +from sqlbuild.runtime.execution_limits.main.cancel_running_statements import ( cancel_running_statements, ) from tests.integration.src.sqlbuild.cli.commands.main._test_types import ( diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_sink_teardown.py b/tests/integration/src/sqlbuild/cli/commands/main/test_sink_teardown.py new file mode 100644 index 0000000000..2ab9d4f25e --- /dev/null +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_sink_teardown.py @@ -0,0 +1,108 @@ +"""A sink's provider session is left open for an abandoned step, and torn down after a normal run.""" + +import os +import signal +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +from tests.integration.src.sqlbuild.cli.commands.main._test_types import ( + SinkAbandonedStepTestCase, + SinkNormalRunTestCase, +) +from tests.integration.src.sqlbuild.cli.commands.main.helpers import build_arguments, sink_project + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signals") +@pytest.mark.parametrize( + "test_case", + [ + SinkAbandonedStepTestCase( + description="a step that ignores the cancel", + parameters="", + step_body='(DIRECTORY / f"{ctx.discovered.item}.running").touch(); time.sleep(120)', + started_markers=("pack.running", "pick.running"), + started_lines=(), + sent_signal=signal.SIGTERM, + expected_exit_code=143, + ), + SinkAbandonedStepTestCase( + description="a step in another provider's first setup", + parameters="gateway_provider: GatewayProvider", + step_body="gateway_provider.model_dump()", + started_markers=("setup-started",), + started_lines=("fulfil[pack] START", "fulfil[pick] START"), + sent_signal=signal.SIGINT, + expected_exit_code=130, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_sink_sharing_providers_when_a_step_is_abandoned_then_nothing_is_torn_down( + test_case: SinkAbandonedStepTestCase, tmp_path: Path +) -> None: + project: Path = sink_project( + tmp_path, parameters=test_case.parameters, body=test_case.step_body + ) + log: Path = tmp_path / "build.log" + with log.open("wb") as output: + process: subprocess.Popen[bytes] = subprocess.Popen( + build_arguments(project), + stdout=output, + stderr=subprocess.STDOUT, + env=os.environ | {"HOME": str(tmp_path)}, + ) + try: + deadline: float = time.monotonic() + 60 + while not ( + all((tmp_path / marker).exists() for marker in test_case.started_markers) + and all(line in log.read_text() for line in test_case.started_lines) + ): + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, log.read_text() + time.sleep(0.05) + process.send_signal(test_case.sent_signal) + exit_code: int = process.wait(timeout=20) + finally: + process.kill() + _ = process.wait(timeout=5) + + journal: list[str] = (tmp_path / "journal.txt").read_text().splitlines() + assert exit_code == test_case.expected_exit_code, log.read_text() + assert "Stopped waiting for fulfil[pack], fulfil[pick] after 5 seconds" in log.read_text() + assert "event invocation_started" in journal + assert "torn down" not in journal + + +@pytest.mark.parametrize( + "test_case", + [ + SinkNormalRunTestCase( + description="the sink's providers are torn down after its last event", + expected_last_line="torn down", + ) + ], + ids=lambda case: case.description, +) +def test_given_a_sink_sharing_providers_when_the_build_finishes_then_providers_are_torn_down( + test_case: SinkNormalRunTestCase, tmp_path: Path +) -> None: + project: Path = sink_project(tmp_path, parameters="", body='journal_provider.write("ran")') + + built: subprocess.CompletedProcess[str] = subprocess.run( + build_arguments(project), + capture_output=True, + text=True, + timeout=120, + check=False, + env=os.environ | {"HOME": str(tmp_path)}, + ) + + journal: list[str] = (tmp_path / "journal.txt").read_text().splitlines() + assert built.returncode == 0, built.stdout + built.stderr + assert journal.count("ran") == 2 + assert "event invocation_completed" in journal + assert journal[-1] == test_case.expected_last_line diff --git a/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py b/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py index 1d0df8d2f3..97748f5ff0 100644 --- a/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py +++ b/tests/integration/src/sqlbuild/cli/recall/test_recall_replacement_sinks.py @@ -1,6 +1,5 @@ from __future__ import annotations -import signal import subprocess import time from pathlib import Path @@ -230,7 +229,7 @@ def test_given_a_lifecycle_sink_slower_than_the_budget_when_building_then_nothin description="Ctrl-C stops the build while the sink sleeps", shutdown_seconds=1.0, sink_sleep_seconds="30", - expected_exit_code=-signal.SIGINT, + expected_exit_code=130, ), ], ids=lambda case: case.description, diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py index 981ebb5efa..c30fa54bde 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py @@ -147,6 +147,15 @@ class WorkerExecutionTestCase: expected_compiles_again: bool = False +@dataclass(frozen=True) +class NodeResultsTestCase(WorkerExecutionTestCase): + description: str + # Each run node as (key, status, rows affected, table rows, rows so far, skipped because of). + expected_node_results: list[tuple[str, str, int | None, int | None, int | None, str | None]] = ( + field(default_factory=list) + ) + + @dataclass(frozen=True) class ClaimedLoadTestCase(WorkerExecutionTestCase): description: str @@ -168,6 +177,28 @@ class CheckExecutionTestCase(WorkerExecutionTestCase): expected_check_outcome: str = "success" +@dataclass(frozen=True) +class RunOutputTestCase(WorkerExecutionTestCase): + description: str + expected_lines: int = 0 + expected_error_lines: list[int] = field(default_factory=list) + expected_logs: list[tuple[str, str, str]] = field(default_factory=list) + + +@dataclass(frozen=True) +class NulLogTestCase(WorkerExecutionTestCase): + description: str + backend: Literal["sqlite", "postgres"] = "sqlite" + expected_logs: list[tuple[str, str]] = field(default_factory=list) + + +@dataclass(frozen=True) +class NulFailureTestCase(WorkerExecutionTestCase): + description: str + backend: Literal["sqlite", "postgres"] = "sqlite" + expected_error_end: str = "" + + @dataclass(frozen=True, kw_only=True) class PersonJourneyTestCase(WorkerExecutionTestCase): description: str @@ -304,6 +335,21 @@ class DevelopmentTestCase: local_config: str = "" +@dataclass(frozen=True) +class DevelopmentExposureTestCase: + description: str + arguments: tuple[str, ...] + expected_status: int + expected_lines: tuple[str, ...] + + +@dataclass(frozen=True) +class DevelopmentAllowHostRefusalTestCase: + description: str + value: str + expected_exit_code: int + + @dataclass(frozen=True) class DevelopmentDiscoveryTestCase: description: str @@ -425,7 +471,9 @@ class DevelopmentMissingSecretsTestCase: description: str first_env_file: str second_env_file: str - # What the warning row shows while the secrets are missing. + # The target's env file, relative to the project. + env_file_name: str + # What the printed warning says while the secrets are missing. expected_warning: tuple[str, ...] @@ -561,7 +609,7 @@ class ChangedJobTestCase(WorkerExecutionTestCase): raw_tables_sql: tuple[str, ...] new_order_sql: str execute: Callable[[Path, str], list[tuple[Any, ...]]] - expected_runs: tuple[tuple[str, frozenset[str], dict[str, int]], ...] + expected_runs: tuple[tuple[str, frozenset[str], dict[str, int], frozenset[str]], ...] @dataclass(frozen=True) @@ -794,3 +842,179 @@ class CheckSensorsTestCase: # The run event's failed checks and failed nodes. expected_failed_checks: list[str] expected_failed_nodes: list[str] + + +@dataclass(frozen=True) +class PythonFailureTestCase(WorkerExecutionTestCase): + description: str + expected_error_start: str = "" + expected_error_end: str = "" + expected_error_below: int = 0 + + +@dataclass(frozen=True) +class SecretAdviceTestCase: + description: str + command: tuple[str, ...] + # The target's env file, relative to the project. + env_file_name: str + expected_help: str + expected_flag_suggested: bool + expected_failure: bool = True + + +@dataclass(frozen=True) +class DevelopmentRepublishTestCase: + description: str + release: str + expected_exit_code: int + expected_items: int + + +@dataclass(frozen=True) +class SessionRepublishTestCase: + description: str + reason: str + expected_exit_code: int + expected_state: str + + +@dataclass(frozen=True) +class NodeStatusTestCase: + description: str + first_depends_on: str + job_select: str + job_settings: str + files: dict[str, str] + expected_statuses_during_second: dict[str, str] + expected_rerun_selection: frozenset[str] + + +@dataclass(frozen=True) +class HungCheckTestCase: + description: str + check_every: str + check_starts_within_seconds: float + expected_message: str + + +@dataclass(frozen=True) +class EmptyDiscoveryTestCase: + description: str + first_items: tuple[str, ...] + expected_nodes: frozenset[str] + expected_kept_items: tuple[str, ...] + + +@dataclass(frozen=True) +class ParallelItemsTestCase: + description: str + first_depends_on: str + job_select: str + expected_status: str + expected_statuses: dict[str, str] + + +@dataclass(frozen=True) +class ItemLogsTestCase: + description: str + depends_on: str + job_select: str + job_settings: str + max_parallel: int + outcomes: dict[str, str] + files: dict[str, str] + expected_statuses: dict[str, str] + + +@dataclass(frozen=True) +class RunningItemsTestCase: + description: str + depends_on: str + job_select: str + job_settings: str + max_parallel: int + files: dict[str, str] + expected_running: int + expected_pending: int + + +@dataclass(frozen=True) +class WaitingCheckTestCase: + description: str + check_seconds: int + expected_finished: bool + expected_restarts: int + + +@dataclass(frozen=True) +class CancelledChainTestCase: + description: str + max_parallel: int + expected_first_run: list[str] + expected_second_run: list[str] + expected_statuses: dict[str, str] + expected_torn_down: bool + + +@dataclass(frozen=True) +class InterruptedStepsTestCase: + description: str + expected_status: str + expected_statuses: dict[str, str] + expected_notice: str + + +@dataclass(frozen=True) +class WaitingRepublishTestCase: + description: str + check_seconds: int + release: str + expected_exit_code: int + expected_check_finished: bool + + +@dataclass(frozen=True) +class KeyedRepublishTestCase: + description: str + role: str + sign_in_arguments: tuple[str, ...] + expected_exit_code: int + expected_stderr: str + expected_generation: int + expected_release: str + + +@dataclass(frozen=True) +class CancelledWriteTestCase: + description: str + job_select: str + job_settings: str + files: dict[str, str] + expected_statuses: dict[str, str] + expected_rerun: list[str] + + +@dataclass(frozen=True) +class UnknownDependencyTestCase: + description: str + first: str + then: str + removed: tuple[str, ...] + missing: str + expected_nodes: frozenset[str] + + +@dataclass(frozen=True) +class UnknownDependencyDiscoverTestCase: + description: str + dependency: str + expected_error: str + + +@dataclass(frozen=True) +class UnknownTagTestCase: + description: str + dependency: str + expected_error: str + expected_status: int diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py index 3117d3bfcd..1cb0fdfcd2 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/docker/compose/helpers.py @@ -224,25 +224,33 @@ def build_projects(self) -> list[str]: def register(self) -> None: self.compose("up", "-d", "--wait", "postgres") location: dict[str, Any] = json.loads( - self.compose("run", "--rm", "--no-deps", "server", "admin", "create-location", "orders") - ) - self.location_id = location["location_id"] - self.environment["SQLBUILD_LOCATION_ID"] = self.location_id - expiry: str = (datetime.now(UTC) + timedelta(hours=1)).isoformat() - credential: dict[str, Any] = json.loads( self.compose( "run", "--rm", "--no-deps", "server", "admin", - "issue-location-token", - self.location_id, - "--expires-at", - expiry, + "create-location", + "orders", + "--json", ) ) - self.environment["SQLBUILD_LOCATION_TOKEN"] = credential["bearer"] + self.location_id = location["location_id"] + self.environment["SQLBUILD_LOCATION_ID"] = self.location_id + expiry: str = (datetime.now(UTC) + timedelta(hours=1)).isoformat() + bearer: str = self.compose( + "run", + "--rm", + "--no-deps", + "-T", + "server", + "admin", + "issue-location-token", + self.location_id, + "--expires-at", + expiry, + ) + self.environment["SQLBUILD_LOCATION_TOKEN"] = bearer.strip() def redeploy(self, version: str) -> None: self.environment["SQLBUILD_LOCATION_IMAGE"] = f"{self.name}:{version}" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py index e94ecbba98..bdaac45e2a 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py @@ -14,6 +14,7 @@ import secrets import select import signal +import socket import sqlite3 import subprocess import sys @@ -33,15 +34,18 @@ from functools import partial from io import StringIO from pathlib import Path -from typing import Any, Literal, cast +from typing import Any, Literal, LiteralString, cast from urllib.error import HTTPError from urllib.parse import quote from urllib.request import Request, urlopen from uuid import uuid4 import duckdb +import psycopg import pytest +from testcontainers.postgres import PostgresContainer +from scripts.native_tests.constants import POSTGRES_IMAGE from sqlbuild._native import ( ColumnMigrationDecision, ColumnMigrationEvent, @@ -158,10 +162,16 @@ def location_process( _ = process.wait(timeout=5) -def stop_location(process: subprocess.Popen[bytes], interpreter_pid: int, log: Path) -> None: - """Exercise graceful `sqb dev` shutdown on SIGTERM and prove its interpreter was reaped.""" +def stop_location( + process: subprocess.Popen[bytes], + interpreter_pid: int, + log: Path, + *, + expected_exit_code: int = 128 + signal.SIGTERM, +) -> None: + """Stop `sqb dev` (143) or `sqb location serve` (0) with SIGTERM; its interpreter is reaped.""" process.send_signal(signal.SIGTERM) - assert process.wait(timeout=15) == 128 + signal.SIGTERM, log.read_text() + assert process.wait(timeout=15) == expected_exit_code, log.read_text() with pytest.raises(ProcessLookupError): os.kill(interpreter_pid, 0) @@ -805,6 +815,14 @@ def wait_for_location_work( return result +def network_address() -> str: + """The IPv4 address other hosts reach this machine on; connecting UDP sends nothing.""" + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as route: + route.connect(("192.0.2.1", 9)) + address: str = route.getsockname()[0] + return address + + def api_address(process: subprocess.Popen[bytes], log: Path) -> str: """Wait for bounded native startup, never publishing an unready address.""" deadline: float = time.monotonic() + 10 @@ -815,9 +833,41 @@ def api_address(process: subprocess.Popen[bytes], log: Path) -> str: return "http://" + log.read_text().partition("Control API ready: ")[2].splitlines()[0] +def control_query( + database: str, statement: LiteralString, *parameters: object +) -> list[tuple[Any, ...]]: + """One committed statement's rows, with `?` placeholders, from either kind of control store.""" + + def on_sqlite() -> list[tuple[Any, ...]]: + with closing(sqlite3.connect(database.removeprefix("sqlite://"))) as control, control: + return control.execute(statement, parameters).fetchall() + + def on_postgres() -> list[tuple[Any, ...]]: + with psycopg.connect(database) as control: + return control.execute(statement.replace("?", "%s"), parameters).fetchall() + + return {True: on_sqlite, False: on_postgres}[database.startswith("sqlite://")]() + + +@contextmanager +def postgres_database() -> Iterator[str]: + """A throwaway PostgreSQL control store.""" + with PostgresContainer(POSTGRES_IMAGE, driver=None) as postgres: + yield postgres.get_connection_url() + + +def control_database(backend: str) -> AbstractContextManager[str | None]: + """The store's URL, or None for the SQLite one each server creates.""" + databases: dict[str, Callable[[], AbstractContextManager[str | None]]] = { + "sqlite": partial(nullcontext, None), + "postgres": postgres_database, + } + return databases[backend]() + + @contextmanager def snapshot_api( - directory: Path, *, server_arguments: tuple[str, ...] = () + directory: Path, *, server_arguments: tuple[str, ...] = (), database_url: str | None = None ) -> Iterator[SnapshotApi]: """Only this fixture seeds the control database; the code location uses HTTP exclusively.""" directory.mkdir() @@ -826,6 +876,12 @@ def snapshot_api( environment.pop("SQLBUILD_CONTROL_DATABASE_URL", None) environment.pop("SQLBUILD_PLATFORM_WEBHOOK_URL", None) environment.pop("SQLBUILD_SECURITY_AUDIT_WEBHOOK_URL", None) + environment["XDG_STATE_HOME"] = str(directory / "state") + environment |= { + True: {}, + False: {"SQLBUILD_CONTROL_DATABASE_URL": str(database_url)}, + }[database_url is None] + database: str = database_url or f"sqlite://{directory}/.sqlbuild/control.sqlite3" with log.open("wb") as stderr: process: subprocess.Popen[bytes] = subprocess.Popen( [ @@ -847,25 +903,25 @@ def snapshot_api( token_id: str = str(uuid4()) bearer: str = f"{token_id}.{secrets.token_hex(32)}" now: datetime = datetime.now(UTC) - with sqlite3.connect(directory / ".sqlbuild/control.sqlite3") as connection: - _ = connection.execute( - "INSERT INTO sqb_locations (location_id,name,created_by,created_at) " - "VALUES (?, 'orders', 'test-admin', ?)", - (location_id, now.isoformat()), - ) - _ = connection.execute( - "INSERT INTO sqb_access_tokens " - "(token_id,secret_hash,location_id,scope_json,created_at,expires_at) " - "VALUES (?,?,?,?,?,?)", - ( - token_id, - hashlib.sha256(bearer.encode()).hexdigest(), - location_id, - json.dumps({"kind": "location", "location_id": location_id}), - now.isoformat(), - (now + timedelta(hours=1)).isoformat(), - ), - ) + _ = control_query( + database, + "INSERT INTO sqb_locations (location_id,name,created_by,created_at) " + "VALUES (?, 'orders', 'test-admin', ?) RETURNING location_id", + location_id, + now.isoformat(), + ) + _ = control_query( + database, + "INSERT INTO sqb_access_tokens " + "(token_id,secret_hash,location_id,scope_json,created_at,expires_at) " + "VALUES (?,?,?,?,?,?) RETURNING token_id", + token_id, + hashlib.sha256(bearer.encode()).hexdigest(), + location_id, + json.dumps({"kind": "location", "location_id": location_id}), + now.isoformat(), + (now + timedelta(hours=1)).isoformat(), + ) yield SnapshotApi(url=url, location_id=location_id, bearer=bearer) finally: process.terminate() @@ -953,6 +1009,7 @@ def scheduled_worker( server_arguments: tuple[str, ...] = (), serve_sensors: bool = True, scheduler_settings: dict[str, Any] | None = None, + database_url: str | None = None, ) -> Iterator[ScheduledWorker]: """Declare, publish and schedule isolated DuckDB work without provisioning claims.""" project: Path = directory / "project" @@ -987,7 +1044,9 @@ def scheduled_worker( "uncooperative": uncooperative_launcher, } with ( - snapshot_api(directory / "control", server_arguments=server_arguments) as api, + snapshot_api( + directory / "control", server_arguments=server_arguments, database_url=database_url + ) as api, launchers[test_case.launcher](directory, executable) as deployment, ): published: subprocess.CompletedProcess[str] = subprocess.run( @@ -1031,10 +1090,17 @@ def scheduled_worker( {"launchers": {deployment.kind: [launcher]}} | (scheduler_settings or {}), ) control_store: Path = directory / "control/.sqlbuild/control.sqlite3" - with sqlite3.connect(control_store) as control: - _ = control.executescript(test_case.store_setup) - test_case.store_edit(control) - monkeypatch.setenv("SQLBUILD_SCHEDULER_TEST_STORE", f"sqlite://{control_store}") + + def edit_sqlite_store() -> None: + with sqlite3.connect(control_store) as control: + _ = control.executescript(test_case.store_setup) + test_case.store_edit(control) + + # A case's store edits are SQLite's. + {True: edit_sqlite_store, False: lambda: None}[database_url is None]() + monkeypatch.setenv( + "SQLBUILD_SCHEDULER_TEST_STORE", database_url or f"sqlite://{control_store}" + ) monkeypatch.setenv( "SQLBUILD_PLATFORM_WEBHOOK_URL", "http://127.0.0.1:1/events?token=synthetic-delivery-credential", @@ -2406,3 +2472,33 @@ def launch_adhoc(worker: ScheduledWorker, command: list[str]) -> dict[str, Any]: session=session, ) == {"applied": True} return wait_for_run(worker.api, worker.process, worker.log, run_id=run_id) + + +# A loader after the items tagged `fulfilment`, which a `+raw_steps` reload runs as ingress. +INGRESS_JOB_SETTINGS: str = "\n[settings]\nreload = true\n" +INGRESS_LOADER_FILES: dict[str, str] = { + "python/ready.py": ( + "from sqlbuild.assets import asset\n" + "from sqlbuild.refs import tag\n\n\n" + '@asset(depends_on=tag("fulfilment"))\n' + "def ready(ctx):\n" + ' """Wait for every step."""\n' + ), + "python/loads.py": ( + "from sqlbuild.loaders import loader\n" + "from python.ready import ready\n\n\n" + "@loader(depends_on=[ready], write_strategy='table', " + "columns=[{'name': 'step', 'type': 'INTEGER'}])\n" + "def fetch_steps(ctx):\n" + ' """Fetch the steps."""\n' + ' return [{"step": 1}]\n\n\n' + "@loader(depends_on=[fetch_steps])\n" + "def raw_steps(ctx):\n" + ' """Load the steps."""\n' + ' return [{"step": 1}]\n' + ), + "sources/raw.yml": ( + "sources:\n - name: raw_steps\n description: Steps.\n" + " managed: true\n write_strategy: table\n" + ), +} diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/person/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/person/helpers.py index 8357d5d100..b4207a7a4f 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/person/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/person/helpers.py @@ -30,7 +30,7 @@ def provision_person(control: Path, command: str, name: str) -> dict[str, Any]: environment.pop("SQLBUILD_CONTROL_DATABASE_URL", None) executable: str = str(Path(sys.executable).with_name("sqb")) created: subprocess.CompletedProcess[str] = subprocess.run( - [executable, "admin", command, name], + [executable, "admin", command, name, "--json"], cwd=control, env=environment, capture_output=True, diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py index f761f6232b..a3db6ac14c 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py @@ -299,11 +299,11 @@ def test_given_an_ad_hoc_command_when_checked_and_launched_then_the_worker_runs_ rewrites={"sources/raw.yml": SOURCES_YML.format(table="missing_orders")}, ), AdhocVerbTestCase( - description="a refused test run leaves its unchecked node skipped", + description="a refused test run leaves its unchecked node not run", prerequisites=[], command=["test", "--select", "customers", "--warehouse", "ANALYST_XS"], expected_selection=["model:customers"], - expected_run_nodes=[("model:customers", "node", "skipped")], + expected_run_nodes=[("model:customers", "node", "not_run")], expected_status="failed", ), ], diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py index b8c6978b06..d6999c9e0b 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_backfill.py @@ -111,6 +111,7 @@ def test_given_explicit_backfill_bounds_when_running_and_rerunning_a_group_then_ run_id, "--reason", "Backfill an explicit order window", + "--json", *test_case.window_arguments, ] rejected: subprocess.CompletedProcess[str] = subprocess.run( @@ -153,6 +154,8 @@ def test_given_explicit_backfill_bounds_when_running_and_rerunning_a_group_then_ check=False, ) assert retried.returncode == 0, retried.stderr + assert not retried.stdout + assert retried.stderr.endswith(f"Queued a rerun of run {run_id} ({retry_id})\n") retry: dict[str, Any] = wait_for_run( worker.api, worker.process, worker.log, run_id=retry_id ) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_chain.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_chain.py new file mode 100644 index 0000000000..f77d48e2b9 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_chain.py @@ -0,0 +1,186 @@ +"""A cancelled chain ends promptly, and a rerun from failure runs exactly what is unfinished.""" + +import sqlite3 +import subprocess +import sys +import time +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + CancelledChainTestCase, + WorkerExecutionTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + scheduled_worker, + wait_for_run, +) + +_CHAIN: str = '''\ +import os +import time +from pathlib import Path + +from providers.marker import MarkerProvider +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) + + +@discover +def fulfilment_plan() -> Discovered: + """A chain of three.""" + return Discovered( + items=[ + Item(id="pick"), + Item(id="pack", depends_on=("pick",)), + Item(id="ship", depends_on=("pack",)), + ], + max_parallel={max_parallel}, + ) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext, marker_provider: MarkerProvider) -> None: + """Record the step and its chain; the first pack ignores any cancel.""" + with (DIRECTORY / "ran.txt").open("a") as ran: + ran.write(f"{{ctx.discovered.item}} {{ctx.root_run_id}}\\n") + if ctx.discovered.item == "pack" and not (DIRECTORY / "pack.pid").exists(): + (DIRECTORY / "pack.pid").write_text(str(os.getpid())) + time.sleep(120) +''' +_PROVIDER: str = '''\ +import os +from pathlib import Path + +from sqlbuild.providers import Provider + + +class MarkerProvider(Provider): + """Say which process tore it down.""" + + def teardown(self) -> None: + Path({directory!r}, f"torn-down.{{os.getpid()}}").touch() +''' + + +@pytest.mark.skipif(sys.platform == "win32", reason="a cancel stops the worker with SIGTERM") +@pytest.mark.parametrize( + "test_case", + [ + CancelledChainTestCase( + description="a parallel step that ignores the cancel is left after 5 seconds", + max_parallel=2, + expected_first_run=["pick", "pack"], + expected_second_run=["pack", "ship"], + expected_statuses={ + "asset:fulfil[pick]": "success", + "asset:fulfil[pack]": "cancelled", + "asset:fulfil[ship]": "cancelled", + }, + expected_torn_down=False, + ), + CancelledChainTestCase( + description="a serial step is interrupted", + max_parallel=1, + expected_first_run=["pick", "pack"], + expected_second_run=["pack", "ship"], + expected_statuses={ + "asset:fulfil[pick]": "success", + "asset:fulfil[pack]": "cancelled", + "asset:fulfil[ship]": "cancelled", + }, + expected_torn_down=True, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_cancel_mid_chain_when_rerun_from_failure_then_only_unfinished_steps_run_in_the_chain( + test_case: CancelledChainTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status="cancelled", + expected_rows=[], + files={ + "python/steps.py": _CHAIN.format( + directory=str(tmp_path), max_parallel=test_case.max_parallel + ), + "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + }, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + 'select = "fulfil"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + ) + }, + ) + sqb: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "admin", + "--database-env", + "SQLBUILD_SCHEDULER_TEST_STORE", + ] + ran: Path = tmp_path / "ran.txt" + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + pidfile: Path = tmp_path / "pack.pid" + deadline: float = time.monotonic() + 40 + while not (pidfile.exists() and pidfile.read_text()): + assert time.monotonic() < deadline, worker.log.read_text() + time.sleep(0.05) + worker_pid: int = int(pidfile.read_text()) + with sqlite3.connect(worker.control_store) as control: + run_id: str = control.execute("SELECT run_id FROM sqb_runs").fetchone()[0] + cancelled: subprocess.CompletedProcess[str] = subprocess.run( + [*sqb, "cancel-run", run_id, "--event-id", str(uuid4()), "--reason", "Stop."], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert cancelled.returncode == 0, cancelled.stderr + cancelled_at: float = time.monotonic() + first: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log, run_id=run_id) + ended_after: float = time.monotonic() - cancelled_at + assert first["status"] == execution.expected_status, worker.log.read_text() + assert ended_after < 30, worker.log.read_text() + with sqlite3.connect(worker.control_store) as control: + statuses: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE run_id=? AND kind='node' AND node_key LIKE 'asset:%'", + (run_id,), + ).fetchall() + ) + assert statuses == test_case.expected_statuses + while Path(f"/proc/{worker_pid}/cmdline").exists(): + assert time.monotonic() < cancelled_at + 30, worker.log.read_text() + time.sleep(0.05) + torn_down: bool = (tmp_path / f"torn-down.{worker_pid}").exists() + assert torn_down == test_case.expected_torn_down + rerun_id: str = str(uuid4()) + rerun: subprocess.CompletedProcess[str] = subprocess.run( + [*sqb, "rerun-run", run_id, "--run-id", rerun_id, "--from-failure"] + + ["--reason", "Finish the chain."], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert rerun.returncode == 0, rerun.stderr + second: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, run_id=rerun_id + ) + assert second["status"] == "success", worker.log.read_text() + + expected: list[str] = test_case.expected_first_run + test_case.expected_second_run + assert ran.read_text().splitlines() == [f"{step} {run_id}" for step in expected] diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_write.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_write.py new file mode 100644 index 0000000000..4ab8971345 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_cancelled_write.py @@ -0,0 +1,199 @@ +"""A cancel reaching every statement leaves the steps that finished succeeded.""" + +import sqlite3 +import subprocess +import sys +import time +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + CancelledWriteTestCase, + WorkerExecutionTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + INGRESS_JOB_SETTINGS, + INGRESS_LOADER_FILES, + scheduled_worker, + wait_for_run, +) + +_STEPS: str = """\ +import time +from pathlib import Path + +from sqlbuild._native import termination_requested +from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) +EXECUTE = DuckDbAdapter._execute +BUSY = "SELECT max(sqrt(step.range)) FROM range(20000000) step" + + +def busy_bookkeeping(self, connection, sql): + \"\"\"A finished step's result and identity writes stay busy until just after the cancel lands.\"\"\" + inserting = sql.lstrip().upper().startswith("INSERT") + if inserting and "_sqlbuild_node_results" in sql: + (DIRECTORY / f"writing-{{threading_name()}}").touch() + if ( + inserting + and ("_sqlbuild_node_results" in sql or "_sqlbuild_fingerprints" in sql) + and not (DIRECTORY / "cancelled").exists() + ): + until = None + while until is None or time.monotonic() < until: + if until is None and termination_requested(): + until = time.monotonic() + 0.5 + EXECUTE(self, connection=connection, sql=BUSY) + if until is None and not (DIRECTORY / "go").exists(): + break + return EXECUTE(self, connection=connection, sql=sql) + + +def threading_name(): + import threading + return threading.current_thread().name + + +DuckDbAdapter._execute = busy_bookkeeping + + +@discover +def fulfilment_plan() -> Discovered: + \"\"\"Five steps at once, and one after them.\"\"\" + steps = [Item(id=step) for step in ("label", "pack", "pick", "ship", "stuck")] + return Discovered(items=[*steps, Item(id="bill", depends_on=("pick",))], max_parallel=5) + + +@asset(for_each=fulfilment_plan, tags=["fulfilment"]) +def fulfil(ctx: AssetContext) -> None: + \"\"\"Three finish before the cancel; ship finishes 2 seconds into it and stuck never.\"\"\" + step = ctx.discovered.item + with (DIRECTORY / "ran.txt").open("a") as ran: + ran.write(f"{{step}}\\n") + if (DIRECTORY / "cancelled").exists(): + return + (DIRECTORY / f"{{step}}.running").touch() + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + if step in ("label", "pack", "pick") and (DIRECTORY / "go").exists(): + return + if step == "ship" and termination_requested(): + time.sleep(2) + return + time.sleep(0.02) +""" +_STATUSES: dict[str, str] = { + "asset:fulfil[bill]": "cancelled", + "asset:fulfil[label]": "success", + "asset:fulfil[pack]": "success", + "asset:fulfil[pick]": "success", + "asset:fulfil[ship]": "success", + "asset:fulfil[stuck]": "cancelled", +} + + +@pytest.mark.skipif(sys.platform == "win32", reason="a cancel stops the worker with SIGTERM") +@pytest.mark.parametrize( + "test_case", + [ + CancelledWriteTestCase( + description="on the read side", + job_select="fulfil", + job_settings="", + files={}, + expected_statuses=_STATUSES, + expected_rerun=["bill", "stuck"], + ), + CancelledWriteTestCase( + description="in ingress", + job_select="+raw_steps", + job_settings=INGRESS_JOB_SETTINGS, + files=INGRESS_LOADER_FILES, + expected_statuses=_STATUSES, + expected_rerun=["bill", "stuck"], + ), + ], + ids=lambda case: case.description, +) +def test_given_steps_finishing_as_a_cancel_lands_when_a_write_is_cancelled_then_all_stay_succeeded( + test_case: CancelledWriteTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status="cancelled", + expected_rows=[], + files={"python/steps.py": _STEPS.format(directory=str(tmp_path))} | test_case.files, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + f'select = "{test_case.job_select}"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + f"{test_case.job_settings}" + ) + }, + ) + sqb: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "admin", + "--database-env", + "SQLBUILD_SCHEDULER_TEST_STORE", + ] + ran: Path = tmp_path / "ran.txt" + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + deadline: float = time.monotonic() + 40 + while len(list(tmp_path.glob("*.running"))) < 5: + assert time.monotonic() < deadline, worker.log.read_text() + time.sleep(0.05) + (tmp_path / "go").touch() + while not list(tmp_path.glob("writing-*")): + assert time.monotonic() < deadline, worker.log.read_text() + time.sleep(0.02) + with sqlite3.connect(worker.control_store) as control: + run_id: str = control.execute("SELECT run_id FROM sqb_runs").fetchone()[0] + cancelled: subprocess.CompletedProcess[str] = subprocess.run( + [*sqb, "cancel-run", run_id, "--event-id", str(uuid4()), "--reason", "Stop."], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert cancelled.returncode == 0, cancelled.stderr + first: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log, run_id=run_id) + assert first["status"] == execution.expected_status, worker.log.read_text() + with sqlite3.connect(worker.control_store) as control: + statuses: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE run_id=? AND kind='node' AND node_key LIKE 'asset:fulfil[%'", + (run_id,), + ).fetchall() + ) + assert statuses == test_case.expected_statuses + ran.write_text("") + (tmp_path / "cancelled").touch() + rerun_id: str = str(uuid4()) + rerun: subprocess.CompletedProcess[str] = subprocess.run( + [*sqb, "rerun-run", run_id, "--run-id", rerun_id, "--from-failure"] + + ["--reason", "Finish the plan."], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert rerun.returncode == 0, rerun.stderr + second: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, run_id=rerun_id + ) + assert second["status"] == "success", worker.log.read_text() + + assert sorted(ran.read_text().split()) == test_case.expected_rerun diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_changed.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_changed.py index cddcad4a5b..08a07138cb 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_changed.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_changed.py @@ -1,5 +1,6 @@ """Scheduled jobs with `changed` run only models whose consumed inputs changed, on DuckDB and SQLite.""" +import sqlite3 import time from dataclasses import replace from pathlib import Path @@ -19,10 +20,23 @@ sqlite_rows, ) -EXPECTED_CHANGED_RUNS: tuple[tuple[str, frozenset[str], dict[str, int]], ...] = ( - ("first run", frozenset({"stg_orders", "stg_customers", "customer_orders"}), {"success": 3}), - ("nothing changed", frozenset(), {"success": 3}), - ("a new order", frozenset({"stg_orders", "customer_orders"}), {"success": 3}), +ALL_MODELS: frozenset[str] = frozenset( + {"model:stg_orders", "model:stg_customers", "model:customer_orders"} +) +EXPECTED_CHANGED_RUNS: tuple[tuple[str, frozenset[str], dict[str, int], frozenset[str]], ...] = ( + ( + "first run", + frozenset({"stg_orders", "stg_customers", "customer_orders"}), + {"success": 3}, + frozenset(), + ), + ("nothing changed", frozenset(), {"success": 3}, ALL_MODELS), + ( + "a new order", + frozenset({"stg_orders", "customer_orders"}), + {"success": 3}, + frozenset({"model:stg_customers"}), + ), ) @@ -83,7 +97,7 @@ def test_given_a_changed_job_when_inputs_change_between_runs_then_only_their_con test_case = replace( test_case, files=changed_job_files(test_case.project_toml), default_job_files={} ) - observed: list[tuple[str, frozenset[str], dict[str, int]]] = [] + observed: list[tuple[str, frozenset[str], dict[str, int], frozenset[str]]] = [] with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: warehouse: Path = worker.project / test_case.warehouse_file for sql in test_case.raw_tables_sql: @@ -106,11 +120,21 @@ def test_given_a_changed_job_when_inputs_change_between_runs_then_only_their_con "WHERE phase = 'started'", ) ) + with sqlite3.connect(worker.control_store) as control: + unchanged: frozenset[str] = frozenset( + key + for (key,) in control.execute( + "SELECT node_key FROM sqb_run_nodes WHERE run_id=? AND kind='node' " + "AND no_change_reason='unchanged since its last build'", + (run["run_id"],), + ) + ) observed.append( ( description, frozenset(row[1] for row in started - recorded), run["node_counts_json"], + unchanged, ) ) recorded |= started diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py index 8d38e9e19f..1807f403d1 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev.py @@ -25,7 +25,9 @@ duckshop_orchestration, ) from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + DevelopmentAllowHostRefusalTestCase, DevelopmentDiscoveryTestCase, + DevelopmentExposureTestCase, DevelopmentInvalidEnvFileTestCase, DevelopmentSecretReloadTestCase, DevelopmentTestCase, @@ -172,6 +174,8 @@ def test_given_development_when_reloaded_and_restarted_then_local_scope_and_paus api, process, log, run_id=run_id, target=test_case.target ) assert run["status"] == "success", log.read_text() + # The worker uploads its output before it reports the run finished. + assert list((control.parent / "output/runs" / run_id).rglob("*.zst")), log.read_text() time.sleep(1) assert current_snapshot(api, test_case.target)["record"]["generation"] == 1 with duckdb.connect(str(project / "warehouse.duckdb"), read_only=True) as warehouse: @@ -457,3 +461,86 @@ def test_given_an_unparsable_env_file_when_a_run_starts_then_its_reason_names_th assert run["status"] == test_case.expected_status, log.read_text() assert run["status_reason"] == test_case.expected_reason, log.read_text() assert test_case.secret_text not in log.read_text() + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + DevelopmentExposureTestCase( + "every interface and an allowed name", + ("--host", "0.0.0.0", "--allow-host", "control.example.com"), + 200, + ("No sign-in", " access anyone who can reach 0.0.0.0:"), + ), + ], + ids=lambda case: case.description, +) +def test_given_an_opened_development_server_when_started_then_it_publishes_takes_the_name_and_warns( + test_case: DevelopmentExposureTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files=TYPE_PROOF_FILES + | { + "sqlbuild_project.toml": 'default_target = "development"\n' + + TYPE_PROOF_FILES["sqlbuild_project.toml"] + + '\n[connections.local]\ndatabase = "warehouse.duckdb"\n' + + '[targets.development]\nschema = "main"\n', + "models/orders.sql": TYPE_PROOF_FILES["models/orders.sql"].replace( + "SELECT order_id, amount", "SELECT order_id, CAST(amount AS BIGINT) AS amount" + ), + }, + ) + executable: str = str(Path(sys.executable).with_name("sqb")) + arguments: list[str] = [executable, "dev", "--project-dir", str(project), "--port", "0"] + log: Path = tmp_path / "development.log" + output: Path = tmp_path / "publications.jsonl" + with location_process(arguments + list(test_case.arguments), log, output) as process: + url, identity = wait_for_development_ready(process, log) + api: SnapshotApi = SnapshotApi(url, identity, "local-development") + _ = wait_for_generation(api, "development", 1, process, log) + request: Request = Request( + f"{url}/api/control/bootstrap", + headers={"Host": "control.example.com", "Origin": "https://control.example.com"}, + ) + with urlopen(request, timeout=5) as response: + assert response.status == test_case.expected_status + assert all(line in log.read_text() for line in test_case.expected_lines), log.read_text() + + +@pytest.mark.parametrize( + "test_case", + [ + DevelopmentAllowHostRefusalTestCase("an origin", "https://control.example.com", 2), + DevelopmentAllowHostRefusalTestCase("a wildcard", "*", 2), + DevelopmentAllowHostRefusalTestCase("a port out of range", "control.example.com:70000", 2), + ], + ids=lambda case: case.description, +) +def test_given_an_unusable_allowed_host_when_development_starts_then_it_is_refused_by_name( + test_case: DevelopmentAllowHostRefusalTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files=TYPE_PROOF_FILES + | { + "sqlbuild_project.toml": 'default_target = "development"\n' + + TYPE_PROOF_FILES["sqlbuild_project.toml"] + + '\n[connections.local]\ndatabase = "warehouse.duckdb"\n' + + '[targets.development]\nschema = "main"\n', + }, + ) + executable: str = str(Path(sys.executable).with_name("sqb")) + arguments: list[str] = [executable, "dev", "--project-dir", str(project), "--port", "0"] + started: subprocess.CompletedProcess[str] = subprocess.run( + [*arguments, "--allow-host", test_case.value], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert started.returncode == test_case.expected_exit_code, started.stderr + assert "--allow-host" in started.stderr diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py index c0cb87c492..2278f8f425 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_dev_terminal.py @@ -561,10 +561,25 @@ def test_given_an_env_file_when_developing_then_start_up_names_it_and_r_reloads_ "a provider missing secrets is warned about until .env sets them and r reloads it", "UNRELATED_SETTING=1\n", "WORKER_ENV_REGION_CODE=42\nWORKER_ENV_TOKEN=worker-token\n", + ".env", ( - "Secrets missing", - "region WORKER_ENV_TOKEN, WORKER_ENV_REGION_CODE", - "set them in .env or the environment; press r to reload", + "1 provider has missing secrets", + "providers/region.py:7", + "token \u2190 WORKER_ENV_TOKEN", + "code \u2190 WORKER_ENV_REGION_CODE", + "2 nodes need it (raw_regions, orders)", + "set them in .env and press r", + "then quit and run sqb dev again", + ), + ), + DevelopmentMissingSecretsTestCase( + "the warning names the target's own env file, which r reloads", + "UNRELATED_SETTING=1\n", + "WORKER_ENV_REGION_CODE=42\nWORKER_ENV_TOKEN=worker-token\n", + "development.env", + ( + "set them in development.env and press r", + "then quit and run sqb dev again", ), ), ], @@ -581,6 +596,7 @@ def test_given_a_provider_missing_secrets_when_developing_then_a_warning_names_t 'name = "orders"\nadapter = "duckdb"\ndefault_target = "development"\n' '[connections.local]\ndatabase = "warehouse.duckdb"\n' '[targets.development]\nschema = "main"\n' + f'env_file = "{test_case.env_file_name}"\n' ), "models/orders.sql": ( "MODEL (description 'Orders.', materialized table);\n" @@ -589,7 +605,7 @@ def test_given_a_provider_missing_secrets_when_developing_then_a_warning_names_t } | REGION_PROVIDER_FILES, ) - env_file: Path = project / ".env" + env_file: Path = project / test_case.env_file_name _ = env_file.write_text(test_case.first_env_file) env_file.chmod(0o600) terminal, process = start_development_on_terminal( @@ -599,7 +615,7 @@ def test_given_a_provider_missing_secrets_when_developing_then_a_warning_names_t warned: str = read_terminal_until( terminal, process, - lambda shown: "\u2500 ready " in shown and "press r to reload" in latest_redraw(shown), + lambda shown: "\u2500 ready " in shown and "Secrets missing" in latest_redraw(shown), ) _ = env_file.write_text(test_case.second_env_file) _ = os.write(terminal, b"r") @@ -618,7 +634,7 @@ def test_given_a_provider_missing_secrets_when_developing_then_a_warning_names_t left: list[str] = reap_development(process, project) os.close(terminal) - warning: str = " ".join(latest_redraw(warned).split()) + warning: str = " ".join(re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", warned).split()) assert all(" ".join(part.split()) in warning for part in test_case.expected_warning), warning assert "worker-token" not in warned + reloaded assert exit_code == 128 + signal.SIGTERM, reloaded diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_discovery_check.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_discovery_check.py new file mode 100644 index 0000000000..ef6802c339 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_discovery_check.py @@ -0,0 +1,208 @@ +"""A `check_every` call that never returns holds up neither shutdown nor a waiting request.""" + +import os +import sys +import time +from pathlib import Path + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + HungCheckTestCase, + WaitingCheckTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + location_process, + snapshot_api, + stop_location, + wait_for_generation, +) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files + +_NODES: str = '''\ +import os +import time +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) + + +@discover(check_every={check_every!r}) +def fulfilment_plan() -> Discovered: + """Steps of the fulfilment plan; every call after the first never returns.""" + if (DIRECTORY / "discovered").exists(): + (DIRECTORY / "check.pid").write_text(str(os.getpid())) + while True: + time.sleep(1) + (DIRECTORY / "discovered").touch() + return Discovered(items=[Item(id="pick")]) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext) -> None: + """Run one step.""" +''' +_SLOW_ONCE: str = '''\ +import os +import time +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) + + +@discover(check_every="60s") +def fulfilment_plan() -> Discovered: + """Steps of the fulfilment plan; only the first check is slow.""" + if (DIRECTORY / "discovered").exists() and not (DIRECTORY / "check.pid").exists(): + (DIRECTORY / "check.pid").write_text(str(os.getpid())) + time.sleep({check_seconds}) + (DIRECTORY / "check.done").touch() + (DIRECTORY / "discovered").touch() + return Discovered(items=[Item(id="pick")]) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext) -> None: + """Run one step.""" +''' + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + HungCheckTestCase( + description="SIGTERM during a check that never returns", + check_every="60s", + check_starts_within_seconds=100, + expected_message="Stopped checking discovered set fulfilment_plan", + ) + ], + ids=lambda case: case.description, +) +def test_given_a_check_that_never_returns_when_the_location_is_stopped_then_it_exits_promptly( + test_case: HungCheckTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + nodes: str = _NODES.format(directory=str(tmp_path), check_every=test_case.check_every) + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "python/plan/nodes.py": nodes, + }, + ) + log: Path = tmp_path / "location.log" + with snapshot_api(tmp_path / "control") as api: + arguments: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "--project-dir", + str(project), + "location", + "serve", + "--server", + api.url, + "--location-id", + api.location_id, + "--target", + "development", + ] + environment: dict[str, str] = os.environ | {"SQLBUILD_LOCATION_TOKEN": api.bearer} + with location_process( + arguments, log, tmp_path / "location.stdout", env=environment + ) as process: + pidfile: Path = tmp_path / "check.pid" + deadline: float = time.monotonic() + test_case.check_starts_within_seconds + while not (pidfile.exists() and pidfile.read_text()): + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, log.read_text() + time.sleep(0.2) + stop_location(process, int(pidfile.read_text()), log, expected_exit_code=0) + assert test_case.expected_message in log.read_text() + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + WaitingCheckTestCase( + description="a check that never returns gives way to a waiting publish", + check_seconds=3600, + expected_finished=False, + expected_restarts=1, + ), + WaitingCheckTestCase( + description="a check that finishes inside the 10 seconds is not abandoned", + check_seconds=3, + expected_finished=True, + expected_restarts=0, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_running_check_when_a_publish_waits_then_only_a_check_past_its_grace_is_abandoned( + test_case: WaitingCheckTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _SLOW_ONCE.format( + directory=str(tmp_path), check_seconds=test_case.check_seconds + ), + }, + ) + log: Path = tmp_path / "location.log" + with snapshot_api(tmp_path / "control") as api: + arguments: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "--project-dir", + str(project), + "location", + "serve", + "--server", + api.url, + "--location-id", + api.location_id, + "--target", + "development", + ] + environment: dict[str, str] = os.environ | {"SQLBUILD_LOCATION_TOKEN": api.bearer} + with location_process( + arguments, log, tmp_path / "location.stdout", env=environment + ) as process: + _ = wait_for_generation(api, "development", 1, process, log) + pidfile: Path = tmp_path / "check.pid" + deadline: float = time.monotonic() + 100 + while not pidfile.exists(): + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, log.read_text() + time.sleep(0.2) + (project / "models/orders.sql").write_text( + "MODEL (description 'Orders.');\nSELECT 2 AS order_id\n" + ) + publish_deadline: float = time.monotonic() + 45 + while '"generation":2' not in (tmp_path / "location.stdout").read_text().replace( + " ", "" + ): + assert process.poll() is None, log.read_text() + assert time.monotonic() < publish_deadline, log.read_text() + time.sleep(0.2) + _ = wait_for_generation(api, "development", 2, process, log) + + assert (tmp_path / "check.done").exists() == test_case.expected_finished + assert log.read_text().count("did not finish within 10 seconds") == ( + test_case.expected_restarts + ) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py index f0e16d790d..23a507b8e9 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_docker_worker.py @@ -160,7 +160,7 @@ def test_given_a_pinned_snapshot_when_container_source_drifts_then_no_warehouse_ with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) assert run["status"] == test_case.expected_status, worker.log.read_text() - assert run["node_counts_json"] == {"skipped": 1} + assert run["node_counts_json"] == {"not_run": 1} assert not (worker.project / "warehouse.duckdb").exists() assert worker.docker is not None name: str = f"sqlbuild-{worker.api.location_id}-{run['run_id']}" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_empty_discovery.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_empty_discovery.py new file mode 100644 index 0000000000..7adffd5fce --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_empty_discovery.py @@ -0,0 +1,116 @@ +"""A discovery that finds no items fails its set, at publish and on a `check_every` check.""" + +import os +import sys +from pathlib import Path +from typing import Any + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + EmptyDiscoveryTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + location_health_reports, + location_process, + snapshot_api, + wait_for_generation, + wait_for_log, +) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files + +_NODES: str = '''\ +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +ITEMS = Path({items!r}) + + +@discover(check_every="60s") +def fulfilment_plan() -> Discovered: + """Steps of the fulfilment plan.""" + return Discovered(items=[Item(id=step) for step in ITEMS.read_text().split()]) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext) -> None: + """Run one step.""" +''' +_ERROR: str = "the discover function returned no items" + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + EmptyDiscoveryTestCase( + description="the last good items stay", + first_items=("pick",), + expected_nodes=frozenset({"asset:fulfil[pick]"}), + expected_kept_items=("pick",), + ), + EmptyDiscoveryTestCase( + description="a set that never found items is the placeholder", + first_items=(), + expected_nodes=frozenset({"asset:fulfil[*]"}), + expected_kept_items=(), + ), + ], + ids=lambda case: case.description, +) +def test_given_no_items_when_checking_and_publishing_then_the_set_fails_and_the_location_publishes( + test_case: EmptyDiscoveryTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + items: Path = tmp_path / "items.txt" + items.write_text(" ".join(test_case.first_items)) + nodes: str = _NODES.format(items=str(items)) + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "python/plan/nodes.py": nodes, + }, + ) + log: Path = tmp_path / "location.log" + with snapshot_api(tmp_path / "control") as api: + arguments: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "--project-dir", + str(project), + "location", + "serve", + "--server", + api.url, + "--location-id", + api.location_id, + "--target", + "development", + ] + environment: dict[str, str] = os.environ | {"SQLBUILD_LOCATION_TOKEN": api.bearer} + with location_process( + arguments, log, tmp_path / "location.stdout", env=environment + ) as process: + first: dict[str, Any] = wait_for_generation(api, "development", 1, process, log) + assert frozenset(first["nodes"]) == test_case.expected_nodes, log.read_text() + items.write_text("") + wait_for_log( + process, + log, + f"Discovered set fulfilment_plan check failed: {_ERROR}", + timeout=100, + ) + (project / "python/plan/nodes.py").write_text(nodes + "\n# An edit runs it again.\n") + second: dict[str, Any] = wait_for_generation(api, "development", 2, process, log) + health: str = str(location_health_reports(api)) + + assert frozenset(second["nodes"]) == test_case.expected_nodes, log.read_text() + saved: dict[str, Any] = second["documents"]["discovered"]["fulfilment_plan"] + assert (saved["status"], saved["error"]) == ("failed", _ERROR) + kept: list[dict[str, Any]] = saved.get("result", {"items": []})["items"] + assert tuple(item["id"] for item in kept) == test_case.expected_kept_items + assert "fulfilment_plan" in health and "failed" in health, health diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_installed_recovery.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_installed_recovery.py index 75a91f61d9..3e0703f58d 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_installed_recovery.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_installed_recovery.py @@ -81,7 +81,11 @@ def test_given_postgres_replicas_when_grant_admin_runs_then_only_the_granted_per ) with PostgresContainer(POSTGRES_IMAGE, driver=None) as postgres: url: str = postgres.get_connection_url() - extra: dict[str, str] = {"SQLBUILD_CONTROL_DATABASE_URL": url} + state: Path = tmp_path / "state" + extra: dict[str, str] = { + "SQLBUILD_CONTROL_DATABASE_URL": url, + "XDG_STATE_HOME": str(state), + } people: list[dict[str, Any]] = [] for command, name in [ ("create-user", fixture["first_person"]), @@ -105,6 +109,11 @@ def test_given_postgres_replicas_when_grant_admin_runs_then_only_the_granted_per serve(installation, extra_environment=extra) as first, serve((Path(binary), replica), extra_environment=extra) as second, ): + for started_in in (tmp_path, replica): + assert ( + f"Run output store: file://{state}/sqlbuild/output\n" + in (started_in / "server.log").read_text() + ) previous: tuple[str, str] = login(first, people[0]["name"], fixture["password"]) other: tuple[str, str] = login(second, people[1]["name"], fixture["password"]) for endpoint in [first, second]: diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py new file mode 100644 index 0000000000..31b9c12d30 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py @@ -0,0 +1,164 @@ +"""One Ctrl+C on a worker whose discovered steps run no statement still reports each of them.""" + +import os +import signal +import sqlite3 +import sys +import time +from pathlib import Path +from typing import Any + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + InterruptedStepsTestCase, + WorkerExecutionTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + scheduled_worker, + wait_for_run, +) + +_STEPS: str = '''\ +import os +import time +from pathlib import Path + +from providers.marker import MarkerProvider +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) + + +@discover +def fulfilment_plan() -> Discovered: + """Three steps at once.""" + items = [Item(id="pick"), Item(id="label"), Item(id="pack")] + return Discovered(items=items, max_parallel=len(items)) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext, marker_provider: MarkerProvider) -> None: + """Pick at once, label in the cancel's grace; pack ignores the cancel.""" + step = ctx.discovered.item + (DIRECTORY / f"{{step}}.started").write_text(str(os.getpid())) + if step == "label": + while not (DIRECTORY / "pressed").exists(): + time.sleep(0.05) + # Later than the 0.6 seconds after which a press may force an exit. + time.sleep(1.5) + if step == "pack": + time.sleep(120) +''' +_PROVIDER: str = '''\ +import os +from pathlib import Path + +from sqlbuild.providers import Provider + + +class MarkerProvider(Provider): + """Say which process tore it down.""" + + def teardown(self) -> None: + Path({directory!r}, f"torn-down.{{os.getpid()}}").touch() +''' +# One Ctrl+C may force an exit only while no statement has ever run, so this adapter records none. +_ADAPTER: str = '''\ +from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter + + +class DuckDbUnrecordedAdapter(DuckDbAdapter): + """Run statements without recording them as running.""" + + adapter_name = "duckdb_unrecorded" + + def execute(self, *, connection, sql): + return self._execute(connection=connection, sql=sql) +''' + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signals") +@pytest.mark.parametrize( + "test_case", + [ + InterruptedStepsTestCase( + description="one finished, one finishing in the grace and one ignoring the cancel", + expected_status="partial", + expected_statuses={ + "asset:fulfil[pick]": "success", + "asset:fulfil[label]": "success", + "asset:fulfil[pack]": "cancelled", + }, + expected_notice="Stopped waiting for fulfil[pack] after 5 seconds", + ) + ], + ids=lambda case: case.description, +) +def test_given_python_only_steps_when_the_worker_gets_one_ctrl_c_then_each_is_reported_before_exit( + test_case: InterruptedStepsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status=test_case.expected_status, + expected_rows=[], + files={ + "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb_unrecorded"\n' + '[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n', + "adapters/duckdb_unrecorded.py": _ADAPTER, + "python/steps.py": _STEPS.format(directory=str(tmp_path)), + "providers/marker.py": _PROVIDER.format(directory=str(tmp_path)), + }, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + 'select = "fulfil"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + ) + }, + ) + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + started: Path = tmp_path / "pack.started" + deadline: float = time.monotonic() + 40 + with sqlite3.connect(worker.control_store) as control: + picked: str = ( + "SELECT count(*) FROM sqb_run_nodes " + "WHERE node_key='asset:fulfil[pick]' AND status='success'" + ) + while not ( + control.execute(picked).fetchone()[0] + and (tmp_path / "label.started").exists() + and started.exists() + and started.read_text() + ): + assert time.monotonic() < deadline, worker.log.read_text() + time.sleep(0.05) + worker_pid: int = int(started.read_text()) + os.kill(worker_pid, signal.SIGINT) + (tmp_path / "pressed").touch() + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + # The worker's exit hooks run after its last report, and must tear nothing down either. + exits_by: float = time.monotonic() + 20 + while Path(f"/proc/{worker_pid}/cmdline").exists(): + assert time.monotonic() < exits_by, worker.log.read_text() + time.sleep(0.05) + statuses: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE run_id=? AND kind='node' AND node_key LIKE 'asset:%'", + (run["run_id"],), + ).fetchall() + ) + + assert statuses == test_case.expected_statuses, worker.log.read_text() + assert run["status"] == test_case.expected_status, worker.log.read_text() + assert test_case.expected_notice in worker.log.read_text() + assert not (tmp_path / f"torn-down.{worker_pid}").exists() diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_item_logs.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_item_logs.py new file mode 100644 index 0000000000..a4849aa66a --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_item_logs.py @@ -0,0 +1,169 @@ +"""A worker files each item's `ctx.log` lines under that item, whatever its outcome and path.""" + +import sqlite3 +from itertools import product +from pathlib import Path +from typing import Any + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + ItemLogsTestCase, + WorkerExecutionTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + INGRESS_JOB_SETTINGS, + INGRESS_LOADER_FILES, + scheduled_worker, + wait_for_run, +) + +_LOGGING: str = '''\ +import threading + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import model + +OUTCOMES = {outcomes!r} +MEET = threading.Barrier({max_parallel}, timeout=30) + + +@discover +def fulfilment_plan() -> Discovered: + """Two steps.""" + return Discovered(items=[Item(id=step) for step in OUTCOMES], max_parallel={max_parallel}) + + +@asset(for_each=fulfilment_plan, depends_on={depends_on}, tags=["fulfilment"]) +def fulfil(ctx: AssetContext): + """Log at every level beside the other step, then end as planned.""" + step = ctx.discovered.item + MEET.wait() + ctx.log.info(f"{{step}} info") + ctx.log.warning(f"{{step}} warning") + ctx.log.error(f"{{step}} error") + MEET.wait() + if OUTCOMES[step] == "failed": + raise ValueError("the step failed") + if OUTCOMES[step] == "skipped": + return ctx.skip(reason="nothing to do") +''' + + +@pytest.mark.parametrize( + "test_case", + [ + ItemLogsTestCase( + description="two at once on the read side, one failing", + depends_on='model("orders")', + job_select="orders fulfil", + job_settings="", + max_parallel=2, + outcomes={"pack": "success", "pick": "failed"}, + files={}, + expected_statuses={"asset:fulfil[pack]": "success", "asset:fulfil[pick]": "failed"}, + ), + ItemLogsTestCase( + description="two at once on the read side, one skipping", + depends_on="()", + job_select="fulfil", + job_settings="", + max_parallel=2, + outcomes={"pack": "skipped", "pick": "success"}, + files={}, + expected_statuses={"asset:fulfil[pack]": "skipped", "asset:fulfil[pick]": "success"}, + ), + ItemLogsTestCase( + description="two at once in ingress, one failing", + depends_on="()", + job_select="+raw_steps", + job_settings=INGRESS_JOB_SETTINGS, + max_parallel=2, + outcomes={"pack": "failed", "pick": "success"}, + files=INGRESS_LOADER_FILES, + expected_statuses={"asset:fulfil[pack]": "failed", "asset:fulfil[pick]": "success"}, + ), + ItemLogsTestCase( + description="two at once in ingress, one skipping", + depends_on="()", + job_select="+raw_steps", + job_settings=INGRESS_JOB_SETTINGS, + max_parallel=2, + outcomes={"pack": "success", "pick": "skipped"}, + files=INGRESS_LOADER_FILES, + expected_statuses={"asset:fulfil[pack]": "success", "asset:fulfil[pick]": "skipped"}, + ), + ItemLogsTestCase( + description="one by one on the read side", + depends_on='model("orders")', + job_select="orders fulfil", + job_settings="", + max_parallel=1, + outcomes={"pack": "failed", "pick": "skipped"}, + files={}, + expected_statuses={"asset:fulfil[pack]": "failed", "asset:fulfil[pick]": "skipped"}, + ), + ItemLogsTestCase( + description="one by one in ingress", + depends_on="()", + job_select="+raw_steps", + job_settings=INGRESS_JOB_SETTINGS, + max_parallel=1, + outcomes={"pack": "success", "pick": "failed"}, + files=INGRESS_LOADER_FILES, + expected_statuses={"asset:fulfil[pack]": "success", "asset:fulfil[pick]": "failed"}, + ), + ], + ids=lambda case: case.description, +) +def test_given_items_logging_at_every_level_when_a_worker_runs_them_then_each_keeps_its_own_lines( + test_case: ItemLogsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + steps: str = _LOGGING.format( + outcomes=test_case.outcomes, + max_parallel=test_case.max_parallel, + depends_on=test_case.depends_on, + ) + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status="", + expected_rows=[], + files={"python/steps.py": steps} | test_case.files, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + f'select = "{test_case.job_select}"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + f"{test_case.job_settings}" + ) + }, + ) + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + with sqlite3.connect(worker.control_store) as control: + statuses: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE run_id=? AND kind='node' AND node_key LIKE 'asset:fulfil[%'", + (run["run_id"],), + ).fetchall() + ) + logs: list[tuple[str, str, str]] = control.execute( + "SELECT node_key, level, message FROM sqb_run_node_logs " + "WHERE run_id=? AND node_key LIKE 'asset:%' ORDER BY node_key, level", + (run["run_id"],), + ).fetchall() + output: str = worker.log.read_text() + + assert statuses == test_case.expected_statuses, output + assert logs == [ + (f"asset:fulfil[{step}]", level, f"{step} {level}") + for step, level in product(sorted(test_case.outcomes), ("error", "info", "warning")) + ] diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py index 995ca03d74..1b339743b6 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_job_subsets.py @@ -60,6 +60,7 @@ def test_given_a_published_job_when_an_operator_excludes_a_model_then_only_the_r "development", "--reason", "Rebuild the job without customers", + "--json", ] refused: subprocess.CompletedProcess[str] = subprocess.run( [*request_run, "--run-id", str(uuid4()), "--select", "products"], diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py new file mode 100644 index 0000000000..2151168e92 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py @@ -0,0 +1,185 @@ +"""A worker reports each Python node as it starts and finishes, so a chain keeps finished steps.""" + +import json +import os +import signal +import sqlite3 +import subprocess +import sys +import time +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + NodeStatusTestCase, + WorkerExecutionTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + scheduled_worker, + wait_for_run, +) + +_CHAIN: str = '''\ +import os +import time +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.refs import model + +DIRECTORY = Path({directory!r}) + + +@asset(depends_on={depends_on}) +def pick(ctx: AssetContext) -> None: + """First step.""" + + +@asset(depends_on=pick) +def pack(ctx: AssetContext) -> None: + """Second step, which waits to be interrupted.""" + (DIRECTORY / "pack.pid").write_text(str(os.getpid())) + time.sleep(120) + + +@asset(depends_on=pack) +def ship(ctx: AssetContext) -> None: + """Third step.""" +''' +_STEPS: frozenset[str] = frozenset({"asset:pick", "asset:pack", "asset:ship"}) + + +@pytest.mark.skipif(sys.platform != "linux", reason="the worker is interrupted with SIGKILL") +@pytest.mark.parametrize( + "test_case", + [ + NodeStatusTestCase( + description="a chain ready when the build starts", + first_depends_on="()", + job_select="pick pack ship", + job_settings="", + files={}, + expected_statuses_during_second={ + "asset:pick": "success", + "asset:pack": "running", + "asset:ship": "pending", + }, + expected_rerun_selection=frozenset({"asset:pack", "asset:ship"}), + ), + NodeStatusTestCase( + description="a chain made ready by a finished model", + first_depends_on='model("orders")', + job_select="orders pick pack ship", + job_settings="", + files={}, + expected_statuses_during_second={ + "asset:pick": "success", + "asset:pack": "running", + "asset:ship": "pending", + }, + expected_rerun_selection=frozenset({"asset:pack", "asset:ship"}), + ), + NodeStatusTestCase( + description="an ingress chain ahead of its loader", + first_depends_on="()", + job_select="+raw_steps", + job_settings="\n[settings]\nreload = true\n", + files={ + "python/loads.py": ( + "from sqlbuild.loaders import loader\n" + "from python.steps import ship\n\n\n" + "@loader(depends_on=[ship], write_strategy='table', " + "columns=[{'name': 'step', 'type': 'INTEGER'}])\n" + "def fetch_steps(ctx):\n" + ' """Fetch the steps."""\n' + ' return [{"step": 1}]\n\n\n' + "@loader(depends_on=[fetch_steps])\n" + "def raw_steps(ctx):\n" + ' """Load the steps."""\n' + ' return [{"step": 1}]\n' + ), + "sources/raw.yml": ( + "sources:\n - name: raw_steps\n description: Steps.\n" + " managed: true\n write_strategy: table\n" + ), + }, + expected_statuses_during_second={ + "asset:pick": "success", + "asset:pack": "running", + "asset:ship": "pending", + }, + expected_rerun_selection=frozenset({"asset:pack", "asset:ship"}), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_chain_of_three_when_the_second_is_interrupted_then_the_first_stays_succeeded( + test_case: NodeStatusTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + chain: str = _CHAIN.format(directory=str(tmp_path), depends_on=test_case.first_depends_on) + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status="partial", + expected_rows=[], + files={"python/steps.py": chain} | test_case.files, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + f'select = "{test_case.job_select}"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + f"{test_case.job_settings}" + ) + }, + ) + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + pidfile: Path = tmp_path / "pack.pid" + deadline: float = time.monotonic() + 40 + while not (pidfile.exists() and pidfile.read_text()): + assert time.monotonic() < deadline, worker.log.read_text() + time.sleep(0.05) + with sqlite3.connect(worker.control_store) as control: + during: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes WHERE kind='node'" + ).fetchall() + ) + os.kill(int(pidfile.read_text()), signal.SIGKILL) + assert {key: during[key] for key in _STEPS} == test_case.expected_statuses_during_second + + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + with sqlite3.connect(worker.control_store) as control: + after: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes WHERE kind='node' AND run_id=?", + (run["run_id"],), + ).fetchall() + ) + assert after["asset:pick"] == "success", str(after) + rerun_id: str = str(uuid4()) + requested: subprocess.CompletedProcess[str] = subprocess.run( + [str(Path(sys.executable).with_name("sqb")), "admin"] + + ["--database-env", "SQLBUILD_SCHEDULER_TEST_STORE"] + + ["rerun-run", run["run_id"], "--run-id", rerun_id, "--from-failure"] + + ["--reason", "Retry the interrupted steps."], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert requested.returncode == 0, requested.stderr + with sqlite3.connect(worker.control_store) as control: + selection: list[str] = json.loads( + control.execute( + "SELECT selection_json FROM sqb_runs WHERE run_id=?", (rerun_id,) + ).fetchone()[0] + ) + assert _STEPS.intersection(selection) == test_case.expected_rerun_selection diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_parallel_items.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_parallel_items.py new file mode 100644 index 0000000000..541dd65192 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_parallel_items.py @@ -0,0 +1,262 @@ +"""A worker runs discovered items side by side on real connections, and cancels them cleanly.""" + +import json +import sqlite3 +import subprocess +import sys +import time +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import duckdb +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + ParallelItemsTestCase, + WorkerExecutionTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + scheduled_worker, + wait_for_run, +) + +_TOGETHER: str = '''\ +import threading + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import model + +STEPS = ("label", "pack", "pick", "ship") +MEET = threading.Barrier(len(STEPS), timeout=30) + + +@discover +def fulfilment_plan() -> Discovered: + """Four steps that run at once.""" + return Discovered(items=[Item(id=step) for step in STEPS], max_parallel=len(STEPS)) + + +@asset(for_each=fulfilment_plan, depends_on={depends_on}) +def fulfil(ctx: AssetContext): + """Write a table and a result while every other step does.""" + step = ctx.discovered.item + MEET.wait() + for _ in range(STEPS.index(step) + 1): + print(f"printing {{step}}", flush=True) + ctx.execute_sql(f"CREATE OR REPLACE TABLE step_{{step}} AS SELECT '{{step}}' AS step") + count = ctx.query(f"SELECT count(*) FROM step_{{step}}").fetchall()[0][0] + MEET.wait() + return ctx.result(payload={{"step": step, "count": count}}) +''' +_CANCELLED: str = '''\ +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import model + +DIRECTORY = Path({directory!r}) + + +@discover +def fulfilment_plan() -> Discovered: + """A step that finishes, one that fails, two long ones and one that waits.""" + items = [Item(id="done"), Item(id="broken"), Item(id="long_a"), Item(id="long_b")] + return Discovered(items=[*items, Item(id="waiting", depends_on=("long_a",))], max_parallel=4) + + +@asset(for_each=fulfilment_plan, depends_on={depends_on}) +def fulfil(ctx: AssetContext) -> None: + """Run one step.""" + step = ctx.discovered.item + (DIRECTORY / f"{{step}}.started").touch() + if step == "broken": + raise ValueError("broken step") + if step.startswith("long"): + ctx.query("SELECT count(*) FROM range(10000000000000) t(v) WHERE v % 7 = 0").fetchall() +''' + + +@pytest.mark.parametrize( + "test_case", + [ + ParallelItemsTestCase( + description="steps ready when the build starts", + first_depends_on="()", + job_select="fulfil", + expected_status="success", + expected_statuses={ + f"asset:fulfil[{step}]": "success" for step in ("label", "pack", "pick", "ship") + }, + ), + ParallelItemsTestCase( + description="steps made ready by a finished model", + first_depends_on='model("orders")', + job_select="orders fulfil", + expected_status="success", + expected_statuses={ + f"asset:fulfil[{step}]": "success" for step in ("label", "pack", "pick", "ship") + }, + ), + ], + ids=lambda case: case.description, +) +def test_given_concurrent_steps_using_sql_when_a_worker_runs_them_then_writes_and_output_do_not_collide( + test_case: ParallelItemsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status=test_case.expected_status, + expected_rows=[], + files={"python/steps.py": _TOGETHER.format(depends_on=test_case.first_depends_on)}, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + f'select = "{test_case.job_select}"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + ) + }, + ) + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + assert run["status"] == test_case.expected_status, worker.log.read_text() + with sqlite3.connect(worker.control_store) as control: + statuses: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE run_id=? AND kind='node' AND node_key LIKE 'asset:%'", + (run["run_id"],), + ).fetchall() + ) + printed: dict[str, int] = dict( + control.execute( + "SELECT node_key, line_count FROM sqb_run_output_streams " + "WHERE run_id=? AND stream='stdout' AND node_key LIKE 'asset:%'", + (run["run_id"],), + ).fetchall() + ) + with duckdb.connect(str(worker.project / "warehouse.duckdb")) as warehouse: + tables: set[str] = { + name + for (name,) in warehouse.execute( + "SELECT table_name FROM duckdb_tables()" + ).fetchall() + } + + assert statuses == test_case.expected_statuses + steps: dict[str, str] = {key: key[len("asset:fulfil[") : -1] for key in statuses} + assert printed == {key: index + 1 for index, key in enumerate(sorted(steps))} + assert {f"step_{step}" for step in steps.values()} <= tables + + +@pytest.mark.skipif(sys.platform == "win32", reason="a cancel stops the worker with SIGTERM") +@pytest.mark.parametrize( + "test_case", + [ + ParallelItemsTestCase( + description=description, + first_depends_on=depends_on, + job_select=job_select, + expected_status="cancelled", + expected_statuses={ + "asset:fulfil[done]": "success", + "asset:fulfil[broken]": "failed", + "asset:fulfil[long_a]": "cancelled", + "asset:fulfil[long_b]": "cancelled", + "asset:fulfil[waiting]": "cancelled", + }, + ) + for description, depends_on, job_select in ( + ("steps ready when the build starts", "()", "fulfil"), + ("steps made ready by a finished model", 'model("orders")', "orders fulfil"), + ) + ], + ids=lambda case: case.description, +) +def test_given_steps_in_flight_when_cancelled_then_finished_steps_stay_and_are_not_rerun( + test_case: ParallelItemsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + steps: str = _CANCELLED.format(directory=str(tmp_path), depends_on=test_case.first_depends_on) + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status=test_case.expected_status, + expected_rows=[], + files={"python/steps.py": steps}, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + f'select = "{test_case.job_select}"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + ) + }, + ) + sqb: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "admin", + "--database-env", + "SQLBUILD_SCHEDULER_TEST_STORE", + ] + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + deadline: float = time.monotonic() + 40 + with sqlite3.connect(worker.control_store) as control: + progress: str = ( + "SELECT count(*) FROM sqb_run_nodes WHERE kind='node' " + "AND node_key IN ('asset:fulfil[done]', 'asset:fulfil[broken]') " + "AND status IN ('success', 'failed')" + ) + while ( + control.execute(progress).fetchone()[0], + len(list(tmp_path.glob("long_*.started"))), + ) != (2, 2): + assert time.monotonic() < deadline, worker.log.read_text() + time.sleep(0.05) + run_id: str = control.execute("SELECT run_id FROM sqb_runs").fetchone()[0] + cancelled: subprocess.CompletedProcess[str] = subprocess.run( + [*sqb, "cancel-run", run_id, "--event-id", str(uuid4()), "--reason", "Stop."], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert cancelled.returncode == 0, cancelled.stderr + run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log, run_id=run_id) + assert run["status"] == test_case.expected_status, worker.log.read_text() + with sqlite3.connect(worker.control_store) as control: + statuses: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE run_id=? AND kind='node' AND node_key LIKE 'asset:%'", + (run_id,), + ).fetchall() + ) + assert statuses == test_case.expected_statuses, worker.log.read_text() + rerun_id: str = str(uuid4()) + rerun: subprocess.CompletedProcess[str] = subprocess.run( + [*sqb, "rerun-run", run_id, "--run-id", rerun_id, "--from-failure"] + + ["--reason", "Retry."], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert rerun.returncode == 0, rerun.stderr + selection: list[str] = json.loads( + control.execute( + "SELECT selection_json FROM sqb_runs WHERE run_id=?", (rerun_id,) + ).fetchone()[0] + ) + assert set(selection).intersection(test_case.expected_statuses) == ( + set(test_case.expected_statuses) - {"asset:fulfil[done]"} + ) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_republish.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_republish.py new file mode 100644 index 0000000000..fb242e6ecb --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_republish.py @@ -0,0 +1,450 @@ +"""The real CLI republishes a `sqb dev` location, which rediscovers, and reads the new tags back.""" + +import ipaddress +import json +import os +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path +from typing import Any +from urllib.request import Request, urlopen + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + DevelopmentRepublishTestCase, + KeyedRepublishTestCase, + SessionRepublishTestCase, + SnapshotApi, + WaitingRepublishTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + current_snapshot, + location_process, + network_address, + wait_for_development_ready, + wait_for_generation, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.login.helpers import ( + authentication_arguments, + browser, + gateway, + pending_login, + request, + sign_in, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.wheel.cli.helpers import ( + administer, + environment, + serve, + successful, +) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files + +_NODES: str = '''\ +import json +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +PLAN = Path({plan!r}) + + +@discover +def fulfilment_plan() -> Discovered: + """Steps of the fulfilment plan.""" + plan = json.loads(PLAN.read_text()) + return Discovered( + items=[Item(id=step) for step in plan["steps"]], tags={{"release": plan["release"]}} + ) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext) -> None: + """Run one step.""" +''' +_CHECKED: str = '''\ +import json +import time +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover + +DIRECTORY = Path({directory!r}) + + +@discover(check_every="60s") +def fulfilment_plan() -> Discovered: + """Steps of the fulfilment plan; only the first check is slow.""" + plan = json.loads((DIRECTORY / "plan.json").read_text()) + if (DIRECTORY / "discovered").exists() and not (DIRECTORY / "check.started").exists(): + (DIRECTORY / "check.started").touch() + time.sleep({check_seconds}) + (DIRECTORY / "check.done").touch() + (DIRECTORY / "discovered").touch() + return Discovered( + items=[Item(id=step) for step in plan["steps"]], tags={{"release": plan["release"]}} + ) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext) -> None: + """Run one step.""" +''' + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + DevelopmentRepublishTestCase( + description="a republish with a key over HTTP publishes the changed plan", + release="0.58.0", + expected_exit_code=0, + expected_items=2, + ) + ], + ids=lambda case: case.description, +) +def test_given_a_changed_external_plan_when_republishing_then_the_readback_shows_its_tags( + test_case: DevelopmentRepublishTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + plan: Path = tmp_path / "plan.json" + log: Path = tmp_path / "dev.log" + plan.write_text(json.dumps({"steps": ["pick"], "release": "0.57.0"})) + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _NODES.format(plan=str(plan)), + }, + ) + executable: str = str(Path(sys.executable).with_name("sqb")) + with log.open("wb") as output: + process: subprocess.Popen[bytes] = subprocess.Popen( + [executable, "dev", "--project-dir", str(project), "--port", "0"], + stdin=subprocess.DEVNULL, + stdout=output, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + try: + url, location = wait_for_development_ready(process, log) + plan.write_text(json.dumps({"steps": ["pick", "pack"], "release": test_case.release})) + republished: subprocess.CompletedProcess[str] = subprocess.run( + [executable, "location", "republish", "--server", url, "--location-id", location] + + ["--target", "development", "--reason", "deploy", "--wait", "--timeout", "45"], + env=os.environ | {"SQLBUILD_API_KEY": "synthetic-development-key"}, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert republished.returncode == test_case.expected_exit_code, republished.stderr + status: dict[str, Any] = json.loads(republished.stdout) + with urlopen( + f"{url}/api/control/locations/{location}/targets/development/discovered", timeout=5 + ) as response: + readback: dict[str, Any] = json.load(response) + assert readback["snapshot_id"] == status["snapshot_id"] + assert readback["sets"][0]["tags"] == {"release": test_case.release} + assert readback["sets"][0]["items"] == test_case.expected_items + finally: + process.send_signal(signal.SIGINT) + process.wait(timeout=30) + + +@pytest.mark.skipif(sys.platform != "linux", reason="Linux owner-only credential storage") +@pytest.mark.parametrize( + "test_case", + [ + SessionRepublishTestCase( + description="a saved login session queues a republish over HTTPS", + reason="deploy", + expected_exit_code=0, + expected_state="pending", + ) + ], + ids=lambda case: case.description, +) +def test_given_a_saved_login_session_when_republishing_then_the_request_names_the_person( + test_case: SessionRepublishTestCase, tmp_path: Path +) -> None: + binary: str | None = shutil.which("sqb") + assert binary is not None + installation: tuple[Path, Path] = Path(binary), tmp_path + home: Path = tmp_path / "home" + home.mkdir() + values: dict[str, str] = environment({"HOME": str(home)}) + for name in ("DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR", "SQLBUILD_API_KEY"): + values.pop(name, None) + successful(administer(installation, ["create-user", "orders-admin"])) + person: dict[str, Any] = successful( + administer(installation, ["create-principal", "orders-deploy"]) + ) + password: str = "orders-private-password" + successful(administer(installation, ["set-password", person["principal_id"]], password)) + successful(administer(installation, ["grant-admin", person["principal_id"]])) + location: dict[str, Any] = successful(administer(installation, ["create-location", "orders"])) + credential: dict[str, Any] = successful( + administer( + installation, + ["issue-location-token", location["location_id"]] + + ["--expires-at", "2099-01-01T00:00:00Z"], + ) + ) + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "orders"\nadapter = "duckdb"\n' + 'default_target = "production"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.production]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + }, + ) + with gateway(tmp_path) as (origin, certificate, transport): + arguments: tuple[str, ...] = authentication_arguments( + "password", origin, certificate, person["principal_id"] + ) + with serve(installation, authentication_arguments=arguments) as backend: + transport["backend"] = backend.removeprefix("http://") + published: subprocess.CompletedProcess[str] = subprocess.run( + [binary, "--project-dir", str(project), "location", "publish"] + + ["--server", backend, "--location-id", location["location_id"]] + + ["--target", "production", "--generation", "1"], + env=values | {"SQLBUILD_LOCATION_TOKEN": credential["bearer"]}, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert published.returncode == 0, published.stderr + client, _ = browser(origin, certificate) + csrf: str = sign_in(client, origin, "password", person["name"], password) + common: list[str] = ["--server", origin, "--ca-cert", str(certificate)] + with pending_login( + [binary, "login", *common, "--no-browser"], values, tmp_path, tmp_path / "cli.log" + ) as (process, url): + approval: dict[str, Any] = {"browser_code": url.split("#", 1)[1], "approve": True} + approved: int = request( + client, origin + "/api/auth/cli/approve", approval, csrf=csrf + )[0] + assert approved == 204 + process.communicate(timeout=20) + assert process.returncode == 0 + republished: subprocess.CompletedProcess[str] = subprocess.run( + [binary, "location", "republish", *common, "--target", "production"] + + ["--location-id", location["location_id"], "--reason", test_case.reason], + cwd=tmp_path, + env=values, + capture_output=True, + text=True, + timeout=20, + check=False, + ) + assert republished.returncode == test_case.expected_exit_code, republished.stderr + status: dict[str, Any] = json.loads(republished.stdout) + assert status["requested_by"] == person["name"] + assert status["state"] == test_case.expected_state + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + WaitingRepublishTestCase( + description="a check that never returns gives way to the republish", + check_seconds=3600, + release="0.59.0", + expected_exit_code=0, + expected_check_finished=False, + ), + WaitingRepublishTestCase( + description="a check that finishes inside the 10 seconds is not abandoned", + check_seconds=3, + release="0.59.0", + expected_exit_code=0, + expected_check_finished=True, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_republish_waiting_on_a_check_when_the_grace_passes_then_the_republish_completes( + test_case: WaitingRepublishTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + plan: Path = tmp_path / "plan.json" + log: Path = tmp_path / "dev.log" + plan.write_text(json.dumps({"steps": ["pick"], "release": "0.58.0"})) + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _CHECKED.format( + directory=str(tmp_path), check_seconds=test_case.check_seconds + ), + }, + ) + executable: str = str(Path(sys.executable).with_name("sqb")) + with log.open("wb") as output: + process: subprocess.Popen[bytes] = subprocess.Popen( + [executable, "dev", "--project-dir", str(project), "--port", "0"], + stdin=subprocess.DEVNULL, + stdout=output, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + try: + url, location = wait_for_development_ready(process, log) + deadline: float = time.monotonic() + 120 + while not (tmp_path / "check.started").exists(): + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, log.read_text() + time.sleep(0.2) + plan.write_text(json.dumps({"steps": ["pick", "pack"], "release": test_case.release})) + republished: subprocess.CompletedProcess[str] = subprocess.run( + [executable, "location", "republish", "--server", url, "--location-id", location] + + ["--target", "development", "--reason", "deploy", "--wait", "--timeout", "45"], + env=os.environ | {"SQLBUILD_API_KEY": "synthetic-development-key"}, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert republished.returncode == test_case.expected_exit_code, republished.stderr + with urlopen( + f"{url}/api/control/locations/{location}/targets/development/discovered", timeout=5 + ) as response: + readback: dict[str, Any] = json.load(response) + assert readback["sets"][0]["tags"] == {"release": test_case.release} + assert (tmp_path / "check.done").exists() == test_case.expected_check_finished + finally: + process.send_signal(signal.SIGINT) + process.wait(timeout=30) + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + KeyedRepublishTestCase( + description="an operator's key publishes the changed plan", + role="operator", + sign_in_arguments=(), + expected_exit_code=0, + expected_stderr="Republish published a snapshot", + expected_generation=2, + expected_release="0.58.0", + ), + KeyedRepublishTestCase( + description="an operator's key needs neither the password origin nor a CSRF proof", + role="operator", + sign_in_arguments=("--password-origin", "https://control.example.com"), + expected_exit_code=0, + expected_stderr="Republish published a snapshot", + expected_generation=2, + expected_release="0.58.0", + ), + KeyedRepublishTestCase( + description="a viewer's key is refused and nothing is published", + role="viewer", + sign_in_arguments=(), + expected_exit_code=2, + expected_stderr="API rejected the request with HTTP 403", + expected_generation=1, + expected_release="0.57.0", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_service_account_key_over_network_http_when_republishing_then_its_role_decides( + test_case: KeyedRepublishTestCase, tmp_path: Path +) -> None: + executable: Path = Path(sys.executable).with_name("sqb") + installation: tuple[Path, Path] = executable, tmp_path + project: Path = tmp_path / "project" + plan: Path = tmp_path / "plan.json" + log: Path = tmp_path / "location.log" + plan.write_text(json.dumps({"steps": ["pick"], "release": "0.57.0"})) + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _NODES.format(plan=str(plan)), + }, + ) + successful(administer(installation, ["create-user", "orders-admin"])) + created: dict[str, Any] = successful(administer(installation, ["create-location", "orders"])) + location: str = created["location_id"] + credential: dict[str, Any] = successful( + administer( + installation, + ["issue-location-token", location, "--expires-at", "2099-01-01T00:00:00Z"], + ) + ) + account: dict[str, Any] = successful( + administer( + installation, ["create-service-account", "orders-deploy", "--role", test_case.role] + ) + ) + key: str = account["key"] + address: str = network_address() + assert not ipaddress.ip_address(address).is_loopback + with serve( + installation, authentication_arguments=("--host", "0.0.0.0", *test_case.sign_in_arguments) + ) as listening: + port: str = listening.rsplit(":", 1)[1] + api: SnapshotApi = SnapshotApi( + url=f"http://127.0.0.1:{port}", location_id=location, bearer=credential["bearer"] + ) + with location_process( + [str(executable), "--project-dir", str(project), "location", "serve"] + + ["--server", api.url, "--location-id", location, "--target", "development"], + log, + tmp_path / "location.stdout", + env=environment({"SQLBUILD_LOCATION_TOKEN": api.bearer}), + ) as served: + _ = wait_for_generation(api, "development", 1, served, log) + plan.write_text(json.dumps({"steps": ["pick", "pack"], "release": "0.58.0"})) + republished: subprocess.CompletedProcess[str] = subprocess.run( + [str(executable), "location", "republish", "--location-id", location] + + ["--server", f"http://{address}:{port}", "--target", "development"] + + ["--reason", "deploy", "--wait", "--timeout", "45"], + cwd=tmp_path, + env=environment({"SQLBUILD_API_KEY": key, "NO_PROXY": address}), + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert republished.returncode == test_case.expected_exit_code, republished.stderr + assert test_case.expected_stderr in republished.stderr + assert republished.stderr.count("travels unencrypted over HTTP") == 1 + current: dict[str, Any] = current_snapshot(api, "development") + assert current["record"]["generation"] == test_case.expected_generation, log.read_text() + readback_request: Request = Request( + f"{api.url}/api/control/locations/{location}/targets/development/discovered", + headers={"Authorization": f"Bearer {key}"}, + ) + with urlopen(readback_request, timeout=5) as response: + readback: dict[str, Any] = json.load(response) + assert readback["snapshot_id"] == current["record"]["snapshot_id"] + assert readback["sets"][0]["tags"] == {"release": test_case.expected_release} + assert key not in republished.stdout + republished.stderr + assert key not in log.read_text() + (tmp_path / "server.log").read_text() diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py index 9c5caf7b7b..2209900d38 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py @@ -101,6 +101,7 @@ def test_given_a_partial_group_when_retrying_from_failure_then_successful_nodes_ "--from-failure", "--reason", "Retry failed and skipped nodes after fixing warehouse input.", + "--json", ] for expected_applied in [True, False]: requested: subprocess.CompletedProcess[str] = subprocess.run( diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py new file mode 100644 index 0000000000..95e43dedd0 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py @@ -0,0 +1,338 @@ +"""A worker files what each node prints under that node in the output store, with its ctx.log lines.""" + +import json +import sqlite3 +from pathlib import Path +from typing import Any + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + NulFailureTestCase, + NulLogTestCase, + PythonFailureTestCase, + RunOutputTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + control_database, + control_query, + scheduled_worker, + wait_for_run, +) + + +@pytest.mark.parametrize( + "test_case", + [ + RunOutputTestCase( + "a post-hook printing about 50 MB", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "success", + [(17,)], + files={ + "models/orders.sql": ( + "MODEL (description 'Orders.', materialized table,\n" + ' post_hooks [python("chatty")]);\n' + "SELECT 17 AS amount\n" + ), + "hooks/python/chatty.py": ( + "import sys\n\n" + "from sqlbuild.hooks import hook\n\n\n" + "@hook\n" + "def chatty(ctx):\n" + " '''Print a large log and two logged lines.'''\n" + " ctx.log.info('loaded orders')\n" + " block = ''.join(f'order row {n:07d} ' + 'x' * 80 + '\\n' for n in range(1000))\n" + " for _ in range(500):\n" + " sys.stdout.write(block)\n" + " sys.stdout.write('ERROR: one order had no customer\\n')\n" + " sys.stdout.flush()\n" + " ctx.log.warning('1 order had no customer')\n" + ), + }, + expected_lines=500_001, + expected_error_lines=[500_001], + expected_logs=[ + ("model:orders", "info", "loaded orders"), + ("model:orders", "warning", "1 order had no customer"), + ], + ), + RunOutputTestCase( + "a hook logging past the per-node cap", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "success", + [(17,)], + files={ + "models/orders.sql": ( + "MODEL (description 'Orders.', materialized table,\n" + ' post_hooks [python("chatty")]);\n' + "SELECT 17 AS amount\n" + ), + "hooks/python/chatty.py": ( + "from sqlbuild.hooks import hook\n\n\n" + "@hook\n" + "def chatty(ctx):\n" + " '''Log a long line, then more lines than a node reports.'''\n" + " ctx.log.error('x' * 5000)\n" + " for n in range(1, 250):\n" + " ctx.log.info(f'line {n}')\n" + " print('done')\n" + ), + }, + expected_lines=1, + expected_error_lines=[], + expected_logs=[("model:orders", "error", "x" * 4093 + "…")] + + [("model:orders", "info", f"line {n}") for n in range(1, 200)], + ), + ], + ids=lambda case: case.description, +) +def test_given_a_node_printing_a_large_log_when_a_worker_runs_it_then_its_lines_are_filed_under_it( + test_case: RunOutputTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: + run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) + assert run["status"] == test_case.expected_status, worker.log.read_text()[-4000:] + with sqlite3.connect(worker.control_store) as control: + streams: dict[tuple[str, str], int] = { + (node, stream): lines + for node, stream, lines in control.execute( + "SELECT node_key, stream, line_count FROM sqb_run_output_streams " + "WHERE run_id=?", + (run["run_id"],), + ).fetchall() + } + error_lines: list[int] = [ + line + for (line,) in control.execute( + "SELECT node_line FROM sqb_run_output_marks WHERE run_id=? " + "AND node_key='model:orders' AND level='error' ORDER BY node_line", + (run["run_id"],), + ).fetchall() + ] + totals: tuple[int, int] = control.execute( + "SELECT dropped_bytes, omitted_bytes FROM sqb_run_output WHERE run_id=?", + (run["run_id"],), + ).fetchone() + logs: list[tuple[str, str, str]] = control.execute( + "SELECT node_key, level, message FROM sqb_run_node_logs WHERE run_id=? " + "ORDER BY logged_at, event_id", + (run["run_id"],), + ).fetchall() + assert totals == (0, 0), streams + assert (streams[("model:orders", "stdout")], error_lines) == ( + test_case.expected_lines, + test_case.expected_error_lines, + ) + assert any(node == "run" for node, _ in streams), streams + assert logs == test_case.expected_logs + assert any((worker.control_store.parent / "output" / "runs").rglob("*.zst")) + + +@pytest.mark.parametrize( + "test_case", + [ + PythonFailureTestCase( + "an asset failing sixty calls deep", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "partial", + [(17,)], + files={ + "python/assets/score_orders.py": ( + "from sqlbuild.assets import asset\n\n\n" + "def lookup_0(row):\n" + " return row['customer_segment']\n\n\n" + + "".join( + f"def lookup_{n}(row):\n return lookup_{n - 1}(row)\n\n\n" + for n in range(1, 61) + ) + + "@asset(description='Scores orders.')\n" + "def score_orders(ctx):\n" + " return lookup_60({'customer_id': 1})\n" + ), + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Build orders and score them."\n' + 'select = "orders score_orders"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + ), + }, + expected_error_start="Traceback (most recent call last):\n ... ", + expected_error_end="KeyError: 'customer_segment'\n", + expected_error_below=2_000, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_failing_python_node_when_a_worker_runs_it_then_its_run_error_is_the_end_of_its_traceback( + test_case: PythonFailureTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: + run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) + assert run["status"] == test_case.expected_status, worker.log.read_text()[-4000:] + with sqlite3.connect(worker.control_store) as control: + (error,) = control.execute( + "SELECT json_extract(e.payload, '$.change.change.error_message') " + "FROM sqb_run_nodes n JOIN recall_events e ON e.storage_id=n.finished_storage_id " + "WHERE n.run_id=? AND n.node_key LIKE '%score_orders'", + (run["run_id"],), + ).fetchone() + assert ( + error.startswith(test_case.expected_error_start), + error.endswith(test_case.expected_error_end), + len(error) < test_case.expected_error_below, + "in lookup_0" in error, + ) == (True, True, True, True), error + + +NUL_LOG_FILES: dict[str, str] = { + "models/orders.sql": ( + "MODEL (description 'Orders.', materialized table,\n" + ' post_hooks [python("raw")]);\n' + "SELECT 17 AS amount\n" + ), + "hooks/python/raw.py": ( + "from sqlbuild.hooks import hook\n\n\n" + "@hook\n" + "def raw(ctx):\n" + " '''Log text holding NUL.'''\n" + " ctx.log.info('loaded ' + chr(0) + 'orders')\n" + " ctx.log.warning(chr(0) + 'y' * 4096)\n" + ), +} +# NUL goes before the cut, so a message that fits without it keeps its last character. +NUL_LOGS: list[tuple[str, str]] = [("info", "loaded orders"), ("warning", "y" * 4096)] + + +@pytest.mark.parametrize( + "test_case", + [ + NulLogTestCase( + "SQLite", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "success", + [(17,)], + backend="sqlite", + files=NUL_LOG_FILES, + expected_logs=NUL_LOGS, + ), + NulLogTestCase( + "PostgreSQL", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "success", + [(17,)], + backend="postgres", + files=NUL_LOG_FILES, + expected_logs=NUL_LOGS, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_nul_in_a_ctx_log_message_when_a_worker_reports_it_then_the_log_and_finish_are_kept( + test_case: NulLogTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with ( + control_database(test_case.backend) as url, + scheduled_worker(tmp_path, monkeypatch, test_case, database_url=url) as worker, + ): + run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) + database: str = url or f"sqlite://{worker.control_store}" + logs: list[tuple[str, str]] = [ + (level, message) + for level, message in control_query( + database, + "SELECT level, message FROM sqb_run_node_logs " + "WHERE node_key='model:orders' ORDER BY logged_at, event_id", + ) + ] + nodes: list[tuple[str, bool]] = [ + (status, finished is not None) + for status, finished in control_query( + database, + "SELECT status, finished_storage_id FROM sqb_run_nodes " + "WHERE node_key='model:orders' AND kind='node'", + ) + ] + assert (run["status"], nodes, logs) == ( + test_case.expected_status, + [("success", True)], + test_case.expected_logs, + ), worker.log.read_text()[-4000:] + + +NUL_FAILURE_FILES: dict[str, str] = { + "python/assets/score_orders.py": ( + "from sqlbuild.assets import asset\n\n\n" + "@asset(description='Scores orders.')\n" + "def score_orders(ctx):\n" + " raise ValueError('refused ' + chr(0) + 'order 17')\n" + ), + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Build orders and score them."\n' + 'select = "orders score_orders"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + ), +} + + +@pytest.mark.parametrize( + "test_case", + [ + NulFailureTestCase( + "SQLite", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "partial", + [(17,)], + backend="sqlite", + files=NUL_FAILURE_FILES, + expected_error_end="ValueError: refused order 17\n", + ), + NulFailureTestCase( + "PostgreSQL", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "partial", + [(17,)], + backend="postgres", + files=NUL_FAILURE_FILES, + expected_error_end="ValueError: refused order 17\n", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_nul_in_an_exception_when_its_traceback_is_reported_then_the_failed_finish_is_kept( + test_case: NulFailureTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with ( + control_database(test_case.backend) as url, + scheduled_worker(tmp_path, monkeypatch, test_case, database_url=url) as worker, + ): + run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) + finishes: list[tuple[str, str]] = [ + (status, json.loads(payload)["change"]["change"].get("error_message", "")) + for status, payload in control_query( + url or f"sqlite://{worker.control_store}", + "SELECT n.status, CAST(e.payload AS TEXT) FROM sqb_run_nodes n " + "JOIN recall_events e ON e.storage_id=n.finished_storage_id " + "WHERE n.node_key='asset:score_orders'", + ) + ] + assert ( + run["status"], + [ + (status, error.endswith(test_case.expected_error_end), chr(0) in error) + for status, error in finishes + ], + ) == (test_case.expected_status, [("failed", True, False)]), ( + finishes, + worker.log.read_text()[-4000:], + ) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_running_items.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_running_items.py new file mode 100644 index 0000000000..1a0a8f3420 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_running_items.py @@ -0,0 +1,144 @@ +"""A step reads `running` on the server while it runs, and one waiting for a slot doesn't.""" + +import sqlite3 +import time +from collections import Counter +from pathlib import Path +from typing import Any + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + RunningItemsTestCase, + WorkerExecutionTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + INGRESS_JOB_SETTINGS, + INGRESS_LOADER_FILES, + scheduled_worker, + wait_for_run, +) + +_HELD: str = '''\ +import time +from pathlib import Path + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import model + +DIRECTORY = Path({directory!r}) +STEPS = ("label", "pack", "pick") + + +@discover +def fulfilment_plan() -> Discovered: + """Three steps.""" + return Discovered(items=[Item(id=step) for step in STEPS], max_parallel={max_parallel}) + + +@asset(for_each=fulfilment_plan, depends_on={depends_on}, tags=["fulfilment"]) +def fulfil(ctx: AssetContext) -> None: + """Hold the slot until released.""" + (DIRECTORY / f"{{ctx.discovered.item}}.running").touch() + deadline = time.monotonic() + 60 + while not (DIRECTORY / "release").exists() and time.monotonic() < deadline: + time.sleep(0.05) +''' + + +@pytest.mark.parametrize( + "test_case", + [ + RunningItemsTestCase( + description="two slots on the read side", + depends_on='model("orders")', + job_select="orders fulfil", + job_settings="", + max_parallel=2, + files={}, + expected_running=2, + expected_pending=1, + ), + RunningItemsTestCase( + description="two slots in ingress", + depends_on="()", + job_select="+raw_steps", + job_settings=INGRESS_JOB_SETTINGS, + max_parallel=2, + files=INGRESS_LOADER_FILES, + expected_running=2, + expected_pending=1, + ), + RunningItemsTestCase( + description="one by one on the read side", + depends_on="()", + job_select="fulfil", + job_settings="", + max_parallel=1, + files={}, + expected_running=1, + expected_pending=2, + ), + RunningItemsTestCase( + description="one by one in ingress", + depends_on="()", + job_select="+raw_steps", + job_settings=INGRESS_JOB_SETTINGS, + max_parallel=1, + files=INGRESS_LOADER_FILES, + expected_running=1, + expected_pending=2, + ), + ], + ids=lambda case: case.description, +) +def test_given_running_steps_when_reading_the_server_then_only_those_with_a_slot_read_running( + test_case: RunningItemsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + steps: str = _HELD.format( + directory=str(tmp_path), + max_parallel=test_case.max_parallel, + depends_on=test_case.depends_on, + ) + execution: WorkerExecutionTestCase = WorkerExecutionTestCase( + description=test_case.description, + model_sql="SELECT 1 AS amount", + warehouse_query="", + expected_status="success", + expected_rows=[], + files={"python/steps.py": steps} | test_case.files, + default_job_files={ + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Run the steps."\n' + f'select = "{test_case.job_select}"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + f"{test_case.job_settings}" + ) + }, + ) + with scheduled_worker(tmp_path, monkeypatch, execution) as worker: + deadline: float = time.monotonic() + 40 + while len(list(tmp_path.glob("*.running"))) < test_case.expected_running: + assert time.monotonic() < deadline, worker.log.read_text() + time.sleep(0.05) + with sqlite3.connect(worker.control_store) as control: + during: dict[str, str] = dict( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE kind='node' AND node_key LIKE 'asset:fulfil[%'" + ).fetchall() + ) + held: set[str] = {f"asset:fulfil[{marker.stem}]" for marker in tmp_path.glob("*.running")} + (tmp_path / "release").touch() + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + + assert Counter(during.values()) == Counter( + running=test_case.expected_running, pending=test_case.expected_pending + ) + assert {during[key] for key in held} == {"running"} + assert run["status"] == execution.expected_status diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_secret_advice.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_secret_advice.py new file mode 100644 index 0000000000..2a60639e9b --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_secret_advice.py @@ -0,0 +1,90 @@ +"""A missing secret's advice names the env file in use, and the flag only where a command takes it.""" + +import subprocess +from pathlib import Path + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + SecretAdviceTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + REGION_PROVIDER_FILES, + run_sqb, +) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files + +_SET_HERE: str = "set WORKER_ENV_REGION_CODE, WORKER_ENV_TOKEN in this shell or in " + + +@pytest.mark.parametrize( + "test_case", + [ + SecretAdviceTestCase("compile takes the flag", ("compile",), ".env", _SET_HERE, True), + SecretAdviceTestCase("dag takes the flag", ("dag",), ".env", _SET_HERE, True), + SecretAdviceTestCase( + "lineage takes the flag", ("lineage", "orders"), ".env", _SET_HERE, True + ), + SecretAdviceTestCase( + "a subcommand takes the flag", ("rules", "run", "SQBRMODEL102"), ".env", _SET_HERE, True + ), + SecretAdviceTestCase( + "plan lists what can't run instead of failing", + ("plan",), + ".env", + "Can't run: provider region needs WORKER_ENV_REGION_CODE, WORKER_ENV_TOKEN " + "(missing from the environment and from ", + False, + expected_failure=False, + ), + SecretAdviceTestCase("freshness doesn't", ("freshness",), ".env", _SET_HERE, False), + SecretAdviceTestCase("janitor doesn't", ("janitor",), ".env", _SET_HERE, False), + SecretAdviceTestCase( + "a subcommand doesn't", ("scenario", "test"), ".env", _SET_HERE, False + ), + SecretAdviceTestCase( + "compile names the target's own env file", + ("compile",), + "development.env", + _SET_HERE, + True, + ), + SecretAdviceTestCase( + "build names the target's own env file", + ("build",), + "development.env", + "set each variable in this shell or in ", + False, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_missing_secret_when_a_command_runs_then_the_advice_fits_that_command( + test_case: SecretAdviceTestCase, tmp_path: Path +) -> None: + write_files( + project_dir=tmp_path, + files={ + "sqlbuild_project.toml": ( + 'name = "orders"\nadapter = "duckdb"\ndefault_target = "development"\n' + '[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n' + f'env_file = "{test_case.env_file_name}"\n' + ), + "models/orders.sql": ( + "MODEL (description 'Orders.', materialized table);\n" + 'SELECT CAST(code AS BIGINT) AS amount FROM __source("raw_regions")\n' + ), + } + | REGION_PROVIDER_FILES, + ) + env_file: Path = tmp_path / test_case.env_file_name + _ = env_file.write_text("UNRELATED_SETTING=1\n") + env_file.chmod(0o600) + + result: subprocess.CompletedProcess[str] = run_sqb(tmp_path, "--no-color", *test_case.command) + shown: str = " ".join((result.stdout + result.stderr).split()) + + assert (result.returncode != 0) is test_case.expected_failure, shown + assert test_case.expected_help + test_case.env_file_name in shown, shown + assert ("--allow-missing-secrets" in shown) is test_case.expected_flag_suggested, shown diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_unknown_item_dependency.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_unknown_item_dependency.py new file mode 100644 index 0000000000..e5229e3d2b --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_unknown_item_dependency.py @@ -0,0 +1,282 @@ +"""An item depending on what the project doesn't have fails its set, not the publish.""" + +import os +import subprocess +import sys +from pathlib import Path +from typing import Any +from urllib.error import HTTPError + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + UnknownDependencyDiscoverTestCase, + UnknownDependencyTestCase, + UnknownTagTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + current_snapshot, + location_health_reports, + location_process, + snapshot_api, + wait_for_generation, + wait_for_log, +) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files + +_PLAN: str = '''\ +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import job, model, seed, source, tag + + +@discover +def fulfilment_plan() -> Discovered: + """Steps of the fulfilment plan.""" + return Discovered(items=[Item(id="pack", depends_on=({dependency},))]) + + +@asset(for_each=fulfilment_plan) +def fulfil(ctx: AssetContext) -> None: + """Run one step.""" +''' +_GOOD: str = '''\ +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import job, model, seed, source + + +@discover +def support_plan() -> Discovered: + """Steps of the support plan, after what the project has.""" + after = (model("orders"), source("raw_orders"), seed("regions"), job("orders_job")) + return Discovered(items=[Item(id="triage", depends_on=after)]) + + +@asset(for_each=support_plan) +def support(ctx: AssetContext) -> None: + """Run one step.""" +''' +_KEPT: frozenset[str] = frozenset({"asset:fulfil[pack]", "asset:support[triage]"}) +_PLACEHOLDER: frozenset[str] = frozenset({"asset:fulfil[*]", "asset:support[triage]"}) + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + UnknownDependencyTestCase( + description="an unknown model", + first='model("returns")', + then='model("returns")', + removed=(), + missing="returns", + expected_nodes=_PLACEHOLDER, + ), + UnknownDependencyTestCase( + description="an unknown source", + first='source("returns")', + then='source("returns")', + removed=(), + missing="returns", + expected_nodes=_PLACEHOLDER, + ), + UnknownDependencyTestCase( + description="an unknown seed", + first='seed("returns")', + then='seed("returns")', + removed=(), + missing="returns", + expected_nodes=_PLACEHOLDER, + ), + UnknownDependencyTestCase( + description="an unknown job", + first='job("returns_job")', + then='job("returns_job")', + removed=(), + missing="returns_job", + expected_nodes=_PLACEHOLDER, + ), + UnknownDependencyTestCase( + description="the last good stays while the project still has what it names", + first='model("inventory")', + then='model("returns")', + removed=(), + missing="returns", + expected_nodes=_KEPT, + ), + UnknownDependencyTestCase( + description="a reused set whose model was removed", + first='model("inventory")', + then='model("inventory")', + removed=("models/inventory.sql",), + missing="inventory", + expected_nodes=_PLACEHOLDER, + ), + ], + ids=lambda case: case.description, +) +def test_given_an_item_naming_what_the_project_lacks_when_publishing_then_only_its_set_fails( + test_case: UnknownDependencyTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + first: str = _PLAN.format(dependency=test_case.first) + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "models/inventory.sql": "MODEL (description 'Stock.');\nSELECT 1 AS item_id\n", + "python/plan/nodes.py": first, + "python/support/nodes.py": _GOOD, + "sources/raw.yml": ( + "sources:\n - name: raw_orders\n description: Raw orders.\n schema: main\n" + ), + "seeds/regions.csv": "region_id\n1\n", + "seeds/regions.yml": ( + "seeds:\n - name: regions\n description: Regions.\n columns:\n" + " - name: region_id\n type: INTEGER\n" + ), + "orchestration/jobs/orders_job.toml": 'name = "orders_job"\n' + 'description = "Build the orders."\nselect = "orders"\n', + }, + ) + log: Path = tmp_path / "location.log" + with snapshot_api(tmp_path / "control") as api: + arguments: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "--project-dir", + str(project), + "location", + "serve", + "--server", + api.url, + "--location-id", + api.location_id, + "--target", + "development", + ] + environment: dict[str, str] = os.environ | {"SQLBUILD_LOCATION_TOKEN": api.bearer} + with location_process( + arguments, log, tmp_path / "location.stdout", env=environment + ) as process: + _ = wait_for_generation(api, "development", 1, process, log) + (project / "models/orders.sql").write_text( + "MODEL (description 'Orders.');\nSELECT 2 AS order_id\n" + ) + (project / "python/plan/nodes.py").write_text(_PLAN.format(dependency=test_case.then)) + for removed in test_case.removed: + (project / removed).unlink() + published: dict[str, Any] = wait_for_generation(api, "development", 2, process, log) + health: str = str(location_health_reports(api)) + + assets: set[str] = set(filter(lambda key: key.startswith("asset:"), published["nodes"])) + assert assets == test_case.expected_nodes, log.read_text() + saved: dict[str, Any] = published["documents"]["discovered"] + assert saved["support_plan"]["status"] == "ok" + assert saved["fulfilment_plan"]["status"] == "failed" + error: str = saved["fulfilment_plan"]["error"] + assert "'pack'" in error and f"'{test_case.missing}'" in error, error + assert "fulfilment_plan" in health and "failed" in health, health + + +@pytest.mark.parametrize( + "test_case", + [ + UnknownDependencyDiscoverTestCase( + description="an unknown model", + dependency='model("returns")', + expected_error=( + "Discover function 'fulfilment_plan' failed: item 'pack' depends on model " + "'returns', which the project does not have" + ), + ) + ], + ids=lambda case: case.description, +) +def test_given_an_item_naming_what_the_project_lacks_when_compiling_with_discover_then_it_stops( + test_case: UnknownDependencyDiscoverTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _PLAN.format(dependency=test_case.dependency), + }, + ) + + compiled: subprocess.CompletedProcess[str] = subprocess.run( + [str(Path(sys.executable).with_name("sqb")), "--no-color", "--project-dir", str(project)] + + ["compile", "--discover"], + capture_output=True, + text=True, + timeout=120, + check=False, + env=os.environ | {"HOME": str(tmp_path)}, + ) + + assert compiled.returncode != 0, compiled.stdout + assert test_case.expected_error in compiled.stdout + compiled.stderr + + +@pytest.mark.skipif(sys.platform == "win32", reason="Unix signal and process ownership contract") +@pytest.mark.parametrize( + "test_case", + [ + UnknownTagTestCase( + description="an unknown tag still fails the whole publish", + dependency='tag("returns")', + expected_error="asset 'fulfil[pack]' depends on tag 'returns', which no node carries", + expected_status=404, + ) + ], + ids=lambda case: case.description, +) +def test_given_an_item_naming_a_tag_no_node_carries_when_publishing_then_nothing_publishes( + test_case: UnknownTagTestCase, tmp_path: Path +) -> None: + project: Path = tmp_path / "project" + write_files( + project_dir=project, + files={ + "sqlbuild_project.toml": 'name = "fulfilment"\nadapter = "duckdb"\n' + 'default_target = "development"\n\n[connection]\ndatabase = "warehouse.duckdb"\n\n' + '[targets.development]\nschema = "main"\n', + "models/orders.sql": "MODEL (description 'Orders.');\nSELECT 1 AS order_id\n", + "python/plan/nodes.py": _PLAN.format(dependency=test_case.dependency), + "python/support/nodes.py": _GOOD.replace( + 'after = (model("orders"), source("raw_orders"), seed("regions"), job("orders_job"))', + 'after = (model("orders"),)', + ), + }, + ) + log: Path = tmp_path / "location.log" + with snapshot_api(tmp_path / "control") as api: + arguments: list[str] = [ + str(Path(sys.executable).with_name("sqb")), + "--project-dir", + str(project), + "location", + "serve", + "--server", + api.url, + "--location-id", + api.location_id, + "--target", + "development", + ] + environment: dict[str, str] = os.environ | {"SQLBUILD_LOCATION_TOKEN": api.bearer} + with location_process( + arguments, log, tmp_path / "location.stdout", env=environment + ) as process: + wait_for_log(process, log, test_case.expected_error, timeout=60) + with pytest.raises(HTTPError) as unpublished: + _ = current_snapshot(api, "development") + + assert unpublished.value.code == test_case.expected_status diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py index 3f43358ad8..6a6d928a3f 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_work.py @@ -98,6 +98,7 @@ def test_given_a_published_location_when_an_owner_requests_work_then_results_ret request_id, "--reason", "Check orders connectivity", + "--json", ] log: Path = tmp_path / "location.log" publications: Path = tmp_path / "publications.jsonl" @@ -125,13 +126,21 @@ def test_given_a_published_location_when_an_owner_requests_work_then_results_ret "healthy": test_case.expected_connection, } read: subprocess.CompletedProcess[str] = subprocess.run( - [executable, "admin", "location-work", request_id], + [executable, "admin", "location-work", request_id, "--json"], env=owner_environment, capture_output=True, text=True, check=True, ) assert json.loads(read.stdout) == result + plain: subprocess.CompletedProcess[str] = subprocess.run( + [executable, "admin", "location-work", request_id], + env=owner_environment, + capture_output=True, + text=True, + check=True, + ) + assert ["state", "completed"] in [line.split() for line in plain.stdout.splitlines()] process.terminate() _ = process.wait(timeout=5) stale_id: str = str(uuid4()) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py index fc3f218001..a565813818 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py @@ -35,6 +35,7 @@ ClaimedWorker, ForcedWorkerStopTestCase, GroupExecutionTestCase, + NodeResultsTestCase, ProviderSecretsHealthTestCase, SnapshotWorkerTestCase, UnclaimedLoadTestCase, @@ -1105,6 +1106,22 @@ def test_given_a_provider_missing_secrets_when_a_scheduled_run_starts_then_it_fa ("model:orders", "skipped", None, "source:raw_regions", False), ("source:raw_regions", "failed", "D012", None, False), ], worker.log.read_text() + nodes_url: str = ( + f"{worker.api.url}/api/locations/{worker.api.location_id}/targets/development" + f"/runs/{run['run_id']}/nodes" + ) + with urlopen( + Request(nodes_url, headers={"Authorization": f"Bearer {worker.api.bearer}"}), timeout=5 + ) as response: + listed: list[dict[str, Any]] = json.load(response) + assert [(node["node_key"], node["missing_secret"]) for node in listed] == [ + ("model:orders", None), + ( + "source:raw_regions", + "provider region: WORKER_ENV_REGION_CODE, WORKER_ENV_TOKEN not set " + "(missing from the location's environment and from .env)", + ), + ], worker.log.read_text() # Nothing connected: the run never opened, so never created, the DuckDB warehouse. assert not (worker.project / "warehouse.duckdb").exists(), worker.log.read_text() @@ -1189,7 +1206,7 @@ def test_given_a_load_the_job_does_not_claim_when_a_worker_plans_then_the_run_is with scheduled_worker(tmp_path, monkeypatch, worker_case) as worker: run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) log: str = worker.log.read_text() - assert (run["status"], run["node_counts_json"]) == ("failed", {"skipped": 1}), log + assert (run["status"], run["node_counts_json"]) == ("failed", {"not_run": 1}), log assert ( f"planned writer {test_case.refused_writer} is outside the frozen run write set" in log ) @@ -1703,7 +1720,7 @@ def test_given_a_rejected_node_report_when_concurrent_then_the_run_stops_before_ "WHERE run_id=? AND kind='node' ORDER BY node_key", (run["run_id"],), ).fetchall() - assert ("model:returns", "skipped", False) in nodes, (nodes, worker.log.read_text()) + assert ("model:returns", "not_run", False) in nodes, (nodes, worker.log.read_text()) with duckdb.connect(str(worker.project / "warehouse.duckdb"), read_only=True) as warehouse: assert warehouse.sql(test_case.warehouse_query).fetchall() == test_case.expected_rows @@ -1822,7 +1839,7 @@ def test_given_a_committed_claim_when_launch_preparation_fails_then_unstarted_wo runs: list[dict[str, Any]] = json.load(response) assert len(runs) == 1 assert runs[0]["status"] == test_case.expected_status, worker.log.read_text() - assert runs[0]["node_counts_json"] == {"skipped": 1} + assert runs[0]["node_counts_json"] == {"not_run": 1} with sqlite3.connect(worker.control_store) as control: assert control.execute("SELECT count(*) FROM sqb_write_claims").fetchone() == (0,) assert control.execute("SELECT count(*) FROM sqb_concurrency_slots").fetchone() == (0,) @@ -2044,6 +2061,7 @@ def test_given_a_running_build_when_the_scheduler_hangs_up_then_its_worker_is_st expected_output_fragments=( "runs that use them stop before the warehouse: " "region WORKER_ENV_TOKEN, region WORKER_ENV_REGION_CODE", + "in the environment the location (or sqb dev) was started with, then restart it.", ), unexpected_output_fragments=(), ), @@ -2200,3 +2218,114 @@ def test_given_a_worker_run_when_its_output_is_captured_then_it_holds_no_json_re assert test_case.expected_recall_events <= events, sorted(events) assert test_case.expected_results in printed, printed assert "{" not in [line.strip() for line in printed.splitlines()], printed + + +NODE_RESULT_FILES: dict[str, str] = { + "python/loaders.py": ( + "from sqlbuild.compiler.python_nodes.types import SkipMode\n" + "from sqlbuild.loaders import loader\n\n\n" + "@loader\n" + "def raw_gate(ctx):\n" + ' """A gate that stays closed."""\n' + ' return ctx.skip(reason="gate closed", mode=SkipMode.HARD)\n\n\n' + "@loader(depends_on=[raw_gate])\n" + "def raw_gated(ctx):\n" + ' """Rows behind the gate."""\n' + ' return [{"gated_id": 1}]\n\n\n' + "@loader\n" + "def raw_events(ctx):\n" + ' """Three events."""\n' + ' return [{"event_id": event_id} for event_id in range(3)]\n' + ), + "sources/raw.yml": ( + "sources:\n" + " - name: raw_gated\n description: Gated rows.\n managed: true\n" + " write_strategy: table\n" + " - name: raw_events\n description: Events.\n managed: true\n" + " write_strategy: table\n" + ), + "models/events.sql": ( + "MODEL (description 'Events.', materialized table);\n" + 'SELECT event_id FROM __source("raw_events")\n' + ), + "models/event_view.sql": ( + "MODEL (description 'Events as a view.', materialized view);\n" + 'SELECT event_id FROM __ref("events")\n' + ), + "models/gated.sql": ( + "MODEL (description 'Gated rows.', materialized table);\n" + 'SELECT gated_id FROM __source("raw_gated")\n' + ), + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Build orders."\n' + 'select = "+orders +event_view +gated"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", starts_at = "2000-01-01T00:00:00Z" }\n' + ), +} + + +@pytest.mark.parametrize( + "test_case", + [ + NodeResultsTestCase( + "rebuilt tables report their rows and a hard skip names itself to what it blocks", + "SELECT 11 AS amount", + "SELECT count(*) FROM events", + "partial", + [(3,)], + files=NODE_RESULT_FILES, + expected_node_results=[ + ("model:event_view", "success", None, None, None, None), + ("model:events", "success", None, 3, None, None), + ("model:gated", "skipped", None, None, None, "source:raw_gate"), + ("model:orders", "success", None, 1, None, None), + ("source:raw_events", "success", 3, None, 3, None), + ("source:raw_gate", "skipped", None, None, None, None), + ("source:raw_gated", "skipped", None, None, None, "source:raw_gate"), + ], + ), + NodeResultsTestCase( + "a worker that cannot import the project leaves every node not run", + "SELECT 11 AS amount", + "", + "failed", + [], + files=NODE_RESULT_FILES + | { + "python/broken.py": ( + "import os\n" + "if 'SQLBUILD_RUN_TOKEN' in os.environ:\n" + " raise RuntimeError('this module breaks inside a worker')\n" + ), + }, + expected_node_results=[ + ("model:event_view", "not_run", None, None, None, None), + ("model:events", "not_run", None, None, None, None), + ("model:gated", "not_run", None, None, None, None), + ("model:orders", "not_run", None, None, None, None), + ("source:raw_events", "not_run", None, None, None, None), + ("source:raw_gate", "not_run", None, None, None, None), + ("source:raw_gated", "not_run", None, None, None, None), + ], + ), + ], + ids=lambda case: case.description, +) +def test_given_a_worker_build_when_it_finishes_then_each_node_reports_what_it_did( + test_case: NodeResultsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + assert run["status"] == test_case.expected_status, worker.log.read_text() + with sqlite3.connect(worker.control_store) as control: + nodes: list[tuple[str, str, int | None, int | None, int | None, str | None]] = list( + control.execute( + "SELECT node_key, status, rows_affected, table_rows, rows_so_far, skipped_because_of " + "FROM sqb_run_nodes WHERE run_id=? AND kind='node' ORDER BY node_key", + (run["run_id"],), + ) + ) + assert nodes == test_case.expected_node_results, f"{nodes}\n{worker.log.read_text()}" diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/wheel/cli/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/wheel/cli/helpers.py index 45c0911a60..73a54c20ed 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/wheel/cli/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/wheel/cli/helpers.py @@ -27,7 +27,7 @@ def administer( """Password input remains on stdin and is never included in process arguments or logs.""" binary, root = installation return subprocess.run( - [str(binary), "admin", *arguments], + [str(binary), "admin", *arguments, "--json"], cwd=root, env=environment(extra_environment), input=password, diff --git a/tests/integration/src/sqlbuild/executor/build/custom/helpers.py b/tests/integration/src/sqlbuild/executor/build/custom/helpers.py index bf06f2c529..cdcdd0b9b0 100644 --- a/tests/integration/src/sqlbuild/executor/build/custom/helpers.py +++ b/tests/integration/src/sqlbuild/executor/build/custom/helpers.py @@ -355,14 +355,14 @@ def build_partition_tracking_fn() -> Callable[[MaterializationContext], Material def materialize(ctx: MaterializationContext) -> MaterializationResult: tracking_table: str = str(ctx.config["tracking_table"]) ctx.logger.debug("checking partition state table=%s", tracking_table) - ctx.log("checking partition state") + ctx.log.info("checking partition state") ctx.execute_sql( f"CREATE TABLE IF NOT EXISTS {tracking_table} (partition_value VARCHAR, run_id VARCHAR)" ) full_sql: str = ctx.sql.replace("@@@partition_start", "'2024-01-01'") full_sql = full_sql.replace("@@@partition_end", "'2024-01-04'") - ctx.log("building initial partition range") + ctx.log.info("building initial partition range") ctx.adapter.create_table_as( connection=ctx.connection, destination=ctx.destination, diff --git a/tests/integration/src/sqlbuild/executor/run/_test_types.py b/tests/integration/src/sqlbuild/executor/run/_test_types.py index 282fb9061c..6469191494 100644 --- a/tests/integration/src/sqlbuild/executor/run/_test_types.py +++ b/tests/integration/src/sqlbuild/executor/run/_test_types.py @@ -1,3 +1,4 @@ +from collections.abc import Callable from dataclasses import dataclass, field from sqlbuild.adapter.contract.types import TablePromotionMode @@ -67,3 +68,13 @@ class AuditSqlResolutionTestCase: attached_target_name: str resolved_target_name: str expected_resolved_sql: str + + +@dataclass(frozen=True) +class RebuiltRowCountTestCase: + """A rebuilt table whose adapter row count read returns or raises.""" + + description: str + promotion_mode: TablePromotionMode + row_count: Callable[..., int | None] + expected_table_rows: int | None diff --git a/tests/integration/src/sqlbuild/executor/run/helpers.py b/tests/integration/src/sqlbuild/executor/run/helpers.py index 208a979a2a..0f7145c2df 100644 --- a/tests/integration/src/sqlbuild/executor/run/helpers.py +++ b/tests/integration/src/sqlbuild/executor/run/helpers.py @@ -49,7 +49,7 @@ def create_python_hook_data(ctx: HookContext, value: int) -> None: ctx.execute_sql( f"CREATE TABLE {ctx.destination.schema}.python_hook_data AS SELECT {value} AS val" ) - ctx.log(f"python pre-hook created data for {ctx.model_name}") + ctx.log.info(f"python pre-hook created data for {ctx.model_name}") def insert_table_hook_log(ctx: HookContext, phase: str) -> None: @@ -414,3 +414,15 @@ def _verify_present_failure_row_count(*, connection: Any, test_case: TableFailur _FAILURE_ROW_COUNT_VERIFIERS: dict[object, Callable[..., None]] = {None: _ignore_failure_row_count} + + +def counted_rows(**_: object) -> int: + """A rebuilt table's row count as an adapter reads it.""" + + return 7 + + +def unreadable_rows(**_: object) -> int: + """A row count read that fails, as when table metadata is unavailable.""" + + raise RuntimeError("table metadata is unavailable") diff --git a/tests/integration/src/sqlbuild/executor/run/test_table_execution.py b/tests/integration/src/sqlbuild/executor/run/test_table_execution.py index 691687feb2..67e7fd9677 100644 --- a/tests/integration/src/sqlbuild/executor/run/test_table_execution.py +++ b/tests/integration/src/sqlbuild/executor/run/test_table_execution.py @@ -13,16 +13,19 @@ from sqlbuild.executor.run.models import ModelExecutionResult from sqlbuild.executor.run.types import ExecutionPhase from tests.integration.src.sqlbuild.executor.run._test_types import ( + RebuiltRowCountTestCase, TableFailureTestCase, TableSuccessTestCase, ) from tests.integration.src.sqlbuild.executor.run.helpers import ( ExtraAuditDefinition, + counted_rows, create_python_hook_data, fail_table_hook, insert_table_hook_log, run_failure_test, run_success_test, + unreadable_rows, verify_failure_warehouse_state, verify_success_warehouse_state, ) @@ -574,3 +577,52 @@ def test_given_fingerprint_failure_when_executing_table_then_succeeds_with_warni verify_success_warehouse_state( result=result, test_case=test_case, adapter=adapter, connection=connection ) + + +@pytest.mark.parametrize( + "test_case", + [ + RebuiltRowCountTestCase( + "a staged rebuild reports the adapter's count", + TablePromotionMode.STAGED, + counted_rows, + 7, + ), + RebuiltRowCountTestCase( + "a staged rebuild whose count read fails still succeeds", + TablePromotionMode.STAGED, + unreadable_rows, + None, + ), + RebuiltRowCountTestCase( + "an immediate rebuild whose count read fails still succeeds", + TablePromotionMode.IMMEDIATE, + unreadable_rows, + None, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_rebuilt_table_when_its_row_count_read_fails_then_the_node_succeeds_without_a_count( + test_case: RebuiltRowCountTestCase, + adapter: DuckDbAdapter, + connection: Any, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(adapter, "rebuilt_table_row_count", test_case.row_count) + + result: ModelExecutionResult = run_success_test( + test_case=TableSuccessTestCase( + description=test_case.description, + setup_sql=(), + model_sql="SELECT 1 AS id", + target_schema="main", + target_name="orders", + promotion_mode=test_case.promotion_mode, + expected_row_count=1, + ), + adapter=adapter, + connection=connection, + ) + + assert result.table_rows == test_case.expected_table_rows diff --git a/tests/integration/src/sqlbuild/executor/run/view/helpers.py b/tests/integration/src/sqlbuild/executor/run/view/helpers.py index 3800e8aa8a..93cb7d9726 100644 --- a/tests/integration/src/sqlbuild/executor/run/view/helpers.py +++ b/tests/integration/src/sqlbuild/executor/run/view/helpers.py @@ -47,7 +47,7 @@ def create_python_view_hook_data(ctx: HookContext, value: int) -> None: ctx.execute_sql( f"CREATE TABLE {ctx.destination.schema}.python_view_data AS SELECT {value} AS val" ) - ctx.log(f"python view pre-hook created data for {ctx.model_name}") + ctx.log.info(f"python view pre-hook created data for {ctx.model_name}") def create_python_view_order_step(ctx: HookContext, source: str, target: str) -> None: diff --git a/tests/unit/scripts/native_module_paths/_helpers/test_host_results.py b/tests/unit/scripts/native_module_paths/_helpers/test_host_results.py index 0bb2761e76..4a74896d63 100644 --- a/tests/unit/scripts/native_module_paths/_helpers/test_host_results.py +++ b/tests/unit/scripts/native_module_paths/_helpers/test_host_results.py @@ -20,7 +20,7 @@ [ HostResultMirrorCase( description="every mirrored result enum and struct matches its Python values or fields", - expected_mirror_count=32, + expected_mirror_count=33, expected_mismatches=(), ) ], diff --git a/tests/unit/scripts/setting_help/__init__.py b/tests/unit/scripts/setting_help/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/scripts/setting_help/_helpers/__init__.py b/tests/unit/scripts/setting_help/_helpers/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/scripts/setting_help/_helpers/_test_types.py b/tests/unit/scripts/setting_help/_helpers/_test_types.py new file mode 100644 index 0000000000..30624661c8 --- /dev/null +++ b/tests/unit/scripts/setting_help/_helpers/_test_types.py @@ -0,0 +1,8 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True) +class RustSettingScanTestCase: + description: str + source: str + expected_lines: tuple[int, ...] diff --git a/tests/unit/scripts/setting_help/_helpers/test_scan.py b/tests/unit/scripts/setting_help/_helpers/test_scan.py new file mode 100644 index 0000000000..da83aae900 --- /dev/null +++ b/tests/unit/scripts/setting_help/_helpers/test_scan.py @@ -0,0 +1,70 @@ +"""The setting scan reads Rust string literals, not the code around them.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from scripts.setting_help.main.find_settings_without_snippet import find_settings_without_snippet +from tests.unit.scripts.setting_help._helpers._test_types import RustSettingScanTestCase + +_PATH: str = "crates/demo/src/lib.rs" + + +@pytest.mark.parametrize( + "test_case", + [ + RustSettingScanTestCase( + description="a match pattern beside a literal names no setting", + source='match outcome {\n Done { healthy: true } => "connection healthy",\n}\n', + expected_lines=(), + ), + RustSettingScanTestCase( + description="a literal naming a setting loosely is found", + source='let help = "set settings.require_sql_analysis to false";\n', + expected_lines=(1,), + ), + RustSettingScanTestCase( + description="a YAML-style setting in a literal is found", + source='let help = "write `require_sql_analysis: false` in the project";\n', + expected_lines=(1,), + ), + RustSettingScanTestCase( + description="a comment is not diagnostic text", + source='// set settings.require_sql_analysis to false\nlet quote = "plain";\n', + expected_lines=(), + ), + RustSettingScanTestCase( + description="a quote char literal doesn't open a string", + source=( + "let quote = '\"';\n" + "let pattern = Done { healthy: true };\n" + 'let text = "set settings.require_sql_analysis to false";\n' + ), + expected_lines=(3,), + ), + RustSettingScanTestCase( + description="a raw string is read whole", + source='let help = r#"say "set settings.require_sql_analysis to false""#;\n', + expected_lines=(1,), + ), + RustSettingScanTestCase( + description="a literal over several lines is reported where it starts", + source='let help = "first line,\n set settings.require_sql_analysis to false";\n', + expected_lines=(1,), + ), + ], + ids=lambda case: case.description, +) +def test_given_rust_source_when_scanning_for_settings_then_only_string_literals_count( + test_case: RustSettingScanTestCase, tmp_path: Path +) -> None: + source: Path = tmp_path / _PATH + source.parent.mkdir(parents=True) + _ = source.write_text(test_case.source, encoding="utf-8") + (tmp_path / "src" / "sqlbuild").mkdir(parents=True) + + findings: list[str] = find_settings_without_snippet(tmp_path) + + assert tuple(int(finding.split(":")[1]) for finding in findings) == test_case.expected_lines diff --git a/tests/unit/src/sqlbuild/adapter/contract/classes/node_logger/_test_types.py b/tests/unit/src/sqlbuild/adapter/contract/classes/node_logger/_test_types.py new file mode 100644 index 0000000000..88a2cca677 --- /dev/null +++ b/tests/unit/src/sqlbuild/adapter/contract/classes/node_logger/_test_types.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass + +from sqlbuild.adapter.contract.types import LogLevel + + +@dataclass(frozen=True) +class NodeLoggerTestCase: + description: str + level: LogLevel + expected_python_level: int + + +@dataclass(frozen=True) +class NodeLoggerCallTestCase: + description: str + message: str + expected_error: type[Exception] diff --git a/tests/unit/src/sqlbuild/adapter/contract/classes/node_logger/test_node_logger.py b/tests/unit/src/sqlbuild/adapter/contract/classes/node_logger/test_node_logger.py new file mode 100644 index 0000000000..60ff5bf3c0 --- /dev/null +++ b/tests/unit/src/sqlbuild/adapter/contract/classes/node_logger/test_node_logger.py @@ -0,0 +1,57 @@ +"""`ctx.log` is a logger: each level records a lifecycle event and logs to the node's logger.""" + +import logging +from typing import Any, cast + +import pytest + +from sqlbuild.adapter.contract.classes.node_logger import NodeLogger +from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder +from sqlbuild.adapter.contract.models import LifeCycleEvent +from sqlbuild.adapter.contract.types import LifeCycleEventKind, LogLevel +from tests.unit.src.sqlbuild.adapter.contract.classes.node_logger._test_types import ( + NodeLoggerCallTestCase, + NodeLoggerTestCase, +) + + +@pytest.mark.parametrize( + "test_case", + [ + NodeLoggerTestCase("info", LogLevel.INFO, logging.INFO), + NodeLoggerTestCase("warning", LogLevel.WARNING, logging.WARNING), + NodeLoggerTestCase("error", LogLevel.ERROR, logging.ERROR), + ], + ids=lambda case: case.description, +) +def test_given_a_node_logger_when_logging_at_a_level_then_the_line_keeps_its_level( + test_case: NodeLoggerTestCase, caplog: pytest.LogCaptureFixture +) -> None: + recorder: StatementRecorder = StatementRecorder() + logger: NodeLogger = NodeLogger(recorder=recorder, logger=logging.getLogger("orders.loader")) + + with caplog.at_level(logging.INFO, logger="orders.loader"): + getattr(logger, test_case.level.value)("loaded 3 orders") + + assert recorder.snapshot() == ( + LifeCycleEvent( + kind=LifeCycleEventKind.LOG, content="loaded 3 orders", level=test_case.level + ), + ) + assert [(record.levelno, record.getMessage()) for record in caplog.records] == [ + (test_case.expected_python_level, "loaded 3 orders") + ] + + +@pytest.mark.parametrize( + "test_case", + [NodeLoggerCallTestCase("a message passed to ctx.log itself", "loaded 3 orders", TypeError)], + ids=lambda case: case.description, +) +def test_given_a_node_logger_when_called_directly_then_it_is_not_callable( + test_case: NodeLoggerCallTestCase, +) -> None: + logger: NodeLogger = NodeLogger(recorder=StatementRecorder(), logger=None) + + with pytest.raises(test_case.expected_error): + cast(Any, logger)(test_case.message) diff --git a/tests/unit/src/sqlbuild/adapters/_test_types.py b/tests/unit/src/sqlbuild/adapters/_test_types.py index e140d0c35f..41dfc07bb7 100644 --- a/tests/unit/src/sqlbuild/adapters/_test_types.py +++ b/tests/unit/src/sqlbuild/adapters/_test_types.py @@ -216,3 +216,11 @@ class SchemaRowCountEstimatesTestCase: expected_reads: int expected_sql_fragment: str metadata_columns: tuple[str, ...] = () + + +@dataclass(frozen=True) +class RebuiltTableRowCountTestCase: + description: str + engine: str + total_rows: int | None + expected_row_count: int | None diff --git a/tests/unit/src/sqlbuild/adapters/test_relation_row_count_estimate.py b/tests/unit/src/sqlbuild/adapters/test_relation_row_count_estimate.py index b1c4ba90af..fb778712eb 100644 --- a/tests/unit/src/sqlbuild/adapters/test_relation_row_count_estimate.py +++ b/tests/unit/src/sqlbuild/adapters/test_relation_row_count_estimate.py @@ -18,6 +18,7 @@ from tests.unit.src.sqlbuild.adapters._test_types import ( BigQueryRowCountEstimateTestCase, DuckDbRowCountEstimateTestCase, + RebuiltTableRowCountTestCase, RelationRowCountEstimateTestCase, SchemaRowCountEstimatesTestCase, ) @@ -520,3 +521,54 @@ def test_given_pages_of_names_when_estimating_schema_row_counts_then_no_read_is_ ] == list(test_case.expected_estimates), test_case.description assert len(connection.executed) == test_case.expected_reads, connection.executed assert test_case.expected_sql_fragment in connection.executed[0], connection.executed + + +@pytest.mark.parametrize( + "test_case", + [ + RebuiltTableRowCountTestCase("plain MergeTree counts exactly", "MergeTree", 42, 42), + RebuiltTableRowCountTestCase( + "replicated MergeTree counts exactly", "ReplicatedMergeTree", 42, 42 + ), + RebuiltTableRowCountTestCase("shared MergeTree counts exactly", "SharedMergeTree", 42, 42), + RebuiltTableRowCountTestCase( + "ReplacingMergeTree counts rows before merges", "ReplacingMergeTree", 42, None + ), + RebuiltTableRowCountTestCase( + "SummingMergeTree counts rows before merges", "SummingMergeTree", 42, None + ), + RebuiltTableRowCountTestCase( + "AggregatingMergeTree counts rows before merges", "AggregatingMergeTree", 42, None + ), + RebuiltTableRowCountTestCase( + "CollapsingMergeTree counts rows before merges", "CollapsingMergeTree", 42, None + ), + RebuiltTableRowCountTestCase( + "replicated ReplacingMergeTree counts rows before merges", + "ReplicatedReplacingMergeTree", + 42, + None, + ), + RebuiltTableRowCountTestCase( + "shared VersionedCollapsingMergeTree counts rows before merges", + "SharedVersionedCollapsingMergeTree", + 42, + None, + ), + RebuiltTableRowCountTestCase("an engine without a count", "MergeTree", None, None), + RebuiltTableRowCountTestCase("a Memory table is not counted", "Memory", 42, None), + ], + ids=lambda case: case.description, +) +def test_given_a_rebuilt_clickhouse_table_when_counting_rows_then_only_exact_engines_report( + test_case: RebuiltTableRowCountTestCase, monkeypatch: pytest.MonkeyPatch +) -> None: + adapter: ClickHouseAdapter = ClickHouseAdapter() + connection: MetadataConnection = MetadataConnection(((test_case.engine, test_case.total_rows),)) + monkeypatch.setattr(adapter, "execute", execute_through_cursor) + + row_count: int | None = adapter.rebuilt_table_row_count( + connection=connection, database=None, schema="dev", name="orders" + ) + + assert row_count == test_case.expected_row_count diff --git a/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/_test_types.py b/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/_test_types.py index 5ab62fd1a4..28ff5ff3d7 100644 --- a/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/_test_types.py +++ b/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/_test_types.py @@ -1,7 +1,7 @@ from dataclasses import dataclass, field from sqlbuild._native import PlanOutput -from sqlbuild.executor.build.models import BuildExecutionResult +from sqlbuild.executor.build.models import BuildExecutionResult, FunctionExecutionResult from sqlbuild.executor.load.models import LoadExecutionResult from sqlbuild.executor.run.models import ModelExecutionResult from sqlbuild.runtime.contracts.types import ExecutionResourceKind @@ -58,6 +58,7 @@ class BuildProgressActiveSpinnerTestCase: description: str node_name: str node_type: ExecutionResourceKind + completed_result: ModelExecutionResult | FunctionExecutionResult expected_fragments: tuple[str, ...] unexpected_fragments: tuple[str, ...] = field(default_factory=tuple) diff --git a/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/test_progress.py b/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/test_progress.py index 1ab6d7b9ce..9845359681 100644 --- a/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/test_progress.py +++ b/tests/unit/src/sqlbuild/cli/commands/shared/_helpers/test_progress.py @@ -1039,6 +1039,11 @@ def isatty(self) -> bool: description="active UDF row uses spinner glyph instead of ellipsis", node_name="is_completed_order", node_type=ExecutionResourceKind.UDF, + completed_result=FunctionExecutionResult( + function_name="is_completed_order", + status=ExecutionStatus.SUCCESS, + function_kind="udf", + ), expected_fragments=("udf", "is_completed_order", "⠋"), unexpected_fragments=("...",), ), @@ -1046,6 +1051,9 @@ def isatty(self) -> bool: description="active view row uses spinner glyph instead of ellipsis", node_name="stg_customers", node_type=ExecutionResourceKind.VIEW, + completed_result=ModelExecutionResult( + model_name="stg_customers", status=ExecutionStatus.SUCCESS + ), expected_fragments=("view", "stg_customers", "⠋"), unexpected_fragments=("...",), ), @@ -1053,6 +1061,9 @@ def isatty(self) -> bool: description="active snapshot row uses snapshot resource type", node_name="customer_snapshot", node_type=ExecutionResourceKind.SNAPSHOT, + completed_result=ModelExecutionResult( + model_name="customer_snapshot", status=ExecutionStatus.SUCCESS + ), expected_fragments=("snapshot", "customer_snapshot", "⠋"), unexpected_fragments=("table",), ), @@ -1071,7 +1082,10 @@ def test_given_active_top_level_node_when_reporting_progress_then_uses_spinner_g ) callbacks.on_node_start(name=test_case.node_name, resource_kind=test_case.node_type) - output: str = stream.getvalue() + try: + output: str = stream.getvalue() + finally: + callbacks.on_node_complete(test_case.completed_result) expected_fragment: str for expected_fragment in test_case.expected_fragments: diff --git a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_descriptions.py b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_descriptions.py index e8de0f63a1..06d53889fe 100644 --- a/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_descriptions.py +++ b/tests/unit/src/sqlbuild/compiler/compile/_helpers/test_descriptions.py @@ -24,6 +24,8 @@ "test_files": "SQL unit tests are named by their subject and expected behaviour", "audit_files": "audits are assertions named by what they check", "audit_factories": "generate audits, which are assertions", + "discover_functions": "list a set's items, not graph resources", + "for_each_assets": "templates of asset nodes; each item's node is checked as an asset", "materialization_files": "materialization strategies, not graph resources", "event_exporters": "runtime event outputs, not graph resources", "command_output_sinks": "runtime command outputs, not graph resources", diff --git a/tests/unit/src/sqlbuild/executor/load/test_models.py b/tests/unit/src/sqlbuild/executor/load/test_models.py index 3beac178a4..3dd12476b7 100644 --- a/tests/unit/src/sqlbuild/executor/load/test_models.py +++ b/tests/unit/src/sqlbuild/executor/load/test_models.py @@ -69,7 +69,7 @@ def test_given_loader_context_when_using_helpers_then_records_and_qualifies_name execute_result: object = context.execute_sql("CREATE TABLE scratch_orders AS SELECT 1") query_result: object = context.query("SELECT * FROM scratch_orders") - context.log("loading scratch orders") + context.log.info("loading scratch orders") qualified_name: str = context.qualify_name( name=test_case.raw_name, database=test_case.database, diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/_test_types.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/_test_types.py index a1bc5d099c..d6bb1aea08 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/_test_types.py @@ -266,3 +266,29 @@ class CheckWarehouseFailureTestCase: upstream_status: PythonNodeStatus expected_error_message: str | None expected_switch_attempts: int + + +@dataclass(frozen=True) +class TracebackTailTestCase: + description: str + depth: int + expected_start: str + expected_end: str + expected_elided: bool + + +@dataclass(frozen=True) +class TracebackRedactionTestCase: + description: str + message: str + expected_kept: str + expected_absent: str + + +@dataclass(frozen=True) +class DiscoveredItemNodeTestCase: + description: str + discovered: dict[str, object] | None + expected_args: dict[str, object] | None + expected_item: str | None + expected_failure: str | None diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py index 633e7554d2..d3b1f51b1b 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/helpers.py @@ -11,6 +11,8 @@ from pathlib import Path from typing import Any, ClassVar, cast +import pytest + from sqlbuild._native import ( CostContext, DiscoveredAssetFunction, @@ -90,7 +92,7 @@ def execute_ordered_test_nodes( sleep=sleep, monotonic=monotonic, ) - run_state.record_result(node_function=node.function, result=result) + run_state.record_result(result=result) results[node.function] = result return tuple(results.values()) @@ -689,3 +691,28 @@ def missing_warehouse_runtime(*, adapter: Any, node: str) -> PythonNodeRuntime: node_warehouses={node: "MISSING_WH"}, session_warehouses=SessionWarehouses(adapter=cast(BaseAdapter, adapter), home="BUILD_WH"), ) + + +def nested_key_error(*, depth: int) -> BaseException: + """Return the KeyError a lookup raises through `depth` distinct calls, with its traceback.""" + + source: str = "def step_0():\n return {'customer_id': 1}['customer_segment']\n" + "".join( + f"def step_{n}():\n return step_{n - 1}()\n" for n in range(1, depth + 1) + ) + steps: dict[str, Any] = {} + exec(compile(source, "steps.py", "exec"), steps) # noqa: S102 + with pytest.raises(KeyError) as raised: + steps[f"step_{depth}"]() + return raised.value + + +def raised_value_error(*, message: str) -> BaseException: + """Return a ValueError with `message`, raised so it has a traceback.""" + + with pytest.raises(ValueError) as raised: + raise ValueError(message) + return raised.value + + +def discovered_step(ctx: object, n: int = 1) -> None: + del ctx, n diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_contexts.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_contexts.py index f3b0a28111..d514b39ba2 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_contexts.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_contexts.py @@ -77,7 +77,7 @@ def test_given_task_context_when_using_helpers_then_records_and_qualifies_names( with caplog.at_level(logging.INFO, logger=test_case.expected_logger_name): execute_result: object = context.execute_sql("CREATE TABLE scratch_orders AS SELECT 1") query_result: object = context.query("SELECT * FROM scratch_orders") - context.log("loading scratch orders") + context.log.info("loading scratch orders") qualified_name: str = context.qualify_name( name=test_case.raw_name, database=test_case.database, diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_discovered_items.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_discovered_items.py new file mode 100644 index 0000000000..1239afd628 --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_discovered_items.py @@ -0,0 +1,78 @@ +from pathlib import Path + +import pytest + +from sqlbuild._native import DiscoveredAssetFunction +from sqlbuild.executor.python_nodes._helpers.discovered_items import ( + discovered_context, + item_args, + placeholder_failure, +) +from sqlbuild.executor.python_nodes.models import DiscoveredContext +from tests.unit.src.sqlbuild.executor.python_nodes._helpers._test_types import ( + DiscoveredItemNodeTestCase, +) +from tests.unit.src.sqlbuild.executor.python_nodes._helpers.helpers import discovered_step + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoveredItemNodeTestCase( + description="an ordinary asset gets no args and no discovered context", + discovered=None, + expected_args=None, + expected_item=None, + expected_failure=None, + ), + DiscoveredItemNodeTestCase( + description="an item's node gets its args and item", + discovered={ + "set": "orders_plan", + "item": "b", + "args": {"n": 2}, + "tags": {"release": "r1"}, + "placeholder": False, + }, + expected_args={"n": 2}, + expected_item="b", + expected_failure=None, + ), + DiscoveredItemNodeTestCase( + description="a placeholder fails with the discovery error", + discovered={"set": "orders_plan", "placeholder": True, "error": "ssh timeout"}, + expected_args={}, + expected_item=None, + expected_failure="never discovered: ssh timeout", + ), + DiscoveredItemNodeTestCase( + description="a placeholder no discovery reached says so", + discovered={"set": "orders_plan", "placeholder": True, "error": None}, + expected_args={}, + expected_item=None, + expected_failure="never discovered: no discovery has run", + ), + ], + ids=lambda case: case.description, +) +def test_given_an_asset_node_when_running_it_then_discovered_items_supply_args_context_or_failure( + test_case: DiscoveredItemNodeTestCase, +) -> None: + node: DiscoveredAssetFunction = DiscoveredAssetFunction( + file_path=Path("/project/python/plan/node.py"), + relative_path=Path("python/plan/node.py"), + name="step[b]", + function=discovered_step, + discovered=test_case.discovered, + ) + context: DiscoveredContext | None = discovered_context(node) + + assert (item_args(node), context and context.item, placeholder_failure(node)) == ( + test_case.expected_args, + test_case.expected_item, + test_case.expected_failure, + ) + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py index 78d68d6a30..ad3184719e 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_execution.py @@ -520,7 +520,7 @@ def test_given_ready_python_node_when_executing_then_uses_existing_run_state( result_store=result_store, ), ) - run_state.record_result(node_function=task_node.function, result=task_result) + run_state.record_result(result=task_result) asset_result: PythonNodeExecutionResult = execute_ready_python_node( node=asset_node, upstream_results=(task_result,), diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_python_checks.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_python_checks.py index f683d4f48d..09cd7c2083 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_python_checks.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_python_checks.py @@ -51,7 +51,6 @@ PythonNodeContextTestAdapter, PythonNodeContextTestResultStore, build_python_check_graph, - check_upstream_task, context_provider_check, provider_check, python_check_function_for_case, @@ -324,7 +323,7 @@ def test_given_python_check_when_executing_then_returns_expected_result( skip_mode=test_case.upstream_skip_mode, skip_reason=test_case.upstream_skip_reason, ) - run_state.record_result(node_function=check_upstream_task, result=upstream_result) + run_state.record_result(result=upstream_result) result_store: PythonNodeContextTestResultStore = PythonNodeContextTestResultStore( { (PythonNodeKind.ASSET.value, "upstream_task"): ( diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_results.py b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_results.py index 7d38269306..fced51b887 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_results.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/_helpers/test_results.py @@ -17,6 +17,7 @@ evaluate_python_node_fan_in, normalize_python_check_return, normalize_python_node_return, + traceback_tail, ) from sqlbuild.executor.python_nodes.models import ( CheckContext, @@ -34,10 +35,14 @@ PythonNodeFailureResultTestCase, PythonNodeFanInPolicyTestCase, PythonNodeReturnNormalizationTestCase, + TracebackRedactionTestCase, + TracebackTailTestCase, ) from tests.unit.src.sqlbuild.executor.python_nodes._helpers.helpers import ( PythonNodeContextTestAdapter, build_check_context, + nested_key_error, + raised_value_error, ) @@ -335,3 +340,109 @@ def test_given_upstream_python_node_results_when_evaluating_fan_in_then_returns_ assert decision.action == test_case.expected_action assert decision.reason == test_case.expected_reason + + +@pytest.mark.parametrize( + "test_case", + [ + TracebackTailTestCase( + description="a short traceback is kept whole", + depth=1, + expected_start="Traceback (most recent call last):\n File ", + expected_end="KeyError: 'customer_segment'\n", + expected_elided=False, + ), + TracebackTailTestCase( + description="a long traceback keeps its header, then its end with the exception", + depth=80, + expected_start="Traceback (most recent call last):\n ... ", + expected_end="KeyError: 'customer_segment'\n", + expected_elided=True, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_python_failure_when_its_traceback_is_kept_then_its_end_fits_the_run_error( + test_case: TracebackTailTestCase, +) -> None: + error: BaseException = nested_key_error(depth=test_case.depth) + result: PythonNodeExecutionResult = build_python_node_failure_result( + node_name="score_orders", kind=PythonNodeKind.ASSET, error=error + ) + detail: str = result.error_detail or "" + assert ( + detail.startswith(test_case.expected_start), + detail.endswith(test_case.expected_end), + "earlier lines" in detail, + len(detail) <= 1_900, + detail == traceback_tail(error=error), + result.error_message, + ) == (True, True, test_case.expected_elided, True, True, "'customer_segment'"), ( + test_case.description, + detail, + ) + + +@pytest.mark.parametrize( + "test_case", + [ + TracebackRedactionTestCase( + description="a secret whose key is on a line the cut drops", + message="password=" + "\n" * 2_000 + "example-value", + expected_kept="ValueError: password=", + expected_absent="example-value", + ), + TracebackRedactionTestCase( + description="a secret whose key is cut from one long line", + message="refused " + + "x" * 100 + + " password=" + + "y" * 400 + + "example-value" + + " z" * 900, + expected_kept="ValueError: refused", + expected_absent="example-value", + ), + TracebackRedactionTestCase( + description="a match only without NUL withholds the whole text", + message="pass\0word=example-value", + expected_kept="[REDACTED]", + expected_absent="example-value", + ), + TracebackRedactionTestCase( + description="a match only as it is withholds the whole text", + message="x\0Bearer example-value", + expected_kept="[REDACTED]", + expected_absent="example-value", + ), + TracebackRedactionTestCase( + description="a match in a long text with NUL withholds it before the cut", + message="x\0Bearer example-value" + "\n refused row" * 400, + expected_kept="[REDACTED]", + expected_absent="example-value", + ), + TracebackRedactionTestCase( + description="a long text with NUL and no match keeps the exception without it", + message="order \0rows refused" + "\n refused row" * 400, + expected_kept="ValueError: order rows refused", + expected_absent="\0", + ), + TracebackRedactionTestCase( + description="a message of many lines keeps the line naming the exception", + message="order rows refused" + "\n refused row" * 400, + expected_kept="ValueError: order rows refused", + expected_absent="password", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_long_error_when_its_traceback_is_cut_then_it_is_redacted_first_and_keeps_the_exception( + test_case: TracebackRedactionTestCase, +) -> None: + detail: str = traceback_tail(error=raised_value_error(message=test_case.message)) + + assert ( + test_case.expected_kept in detail, + test_case.expected_absent not in detail, + len(detail) <= 1_900, + ) == (True, True, True), (test_case.description, detail) diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/classes/_test_types.py b/tests/unit/src/sqlbuild/executor/python_nodes/classes/_test_types.py index 3322b5f7f9..5e9ba2e3dd 100644 --- a/tests/unit/src/sqlbuild/executor/python_nodes/classes/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/python_nodes/classes/_test_types.py @@ -19,3 +19,89 @@ class RuntimeRelationGuardTestCase: owner_label: str = "asset 'export_orders'" owner_kind: HardCodedRelationOwnerKind = HardCodedRelationOwnerKind.NODE upstream_loader_by_source: dict[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class ItemPoolCapTestCase: + description: str + items: tuple[tuple[str, str, int | None], ...] + meet: int + expected_connections: int + expected_most_at_once: int + + +@dataclass(frozen=True) +class ItemPoolOrderTestCase: + description: str + items: tuple[tuple[str, int | None, tuple[str, ...]], ...] + meeting: tuple[str, ...] + expected_seen_before: dict[str, frozenset[str]] + + +@dataclass(frozen=True) +class ItemPoolSerialTestCase: + description: str + max_parallel: int | None + adapter_name: str + expected_threads: int + expected_connections: int + + +@dataclass(frozen=True) +class ItemPoolFailureTestCase: + description: str + outcome: str + expected_first_status: str + + +@dataclass(frozen=True) +class ItemPoolCancelTestCase: + description: str + expected_reported: frozenset[tuple[str, str]] + expected_cancelled: tuple[str, ...] + expected_never_started: str + + +@dataclass(frozen=True) +class ItemPoolWriteTestCase: + description: str + steps: tuple[str, ...] + expected_status: str + + +@dataclass(frozen=True) +class ItemPoolRecordedInterruptTestCase: + description: str + items: tuple[str, ...] + expected_reported: frozenset[tuple[str, str]] + + +@dataclass(frozen=True) +class ItemPoolIgnoredCancelTestCase: + description: str + expected_reported: frozenset[tuple[str, str]] + expected_cancelled: tuple[str, ...] + expected_left_open: int + expected_within_seconds: float + + +@dataclass(frozen=True) +class ItemPoolRepeatedCancelTestCase: + description: str + items: tuple[str, ...] + expected_reported: frozenset[tuple[str, str]] + + +@dataclass(frozen=True) +class ItemPoolResultWriteTestCase: + description: str + write_seconds: float + expected_reported: frozenset[tuple[str, str]] + + +@dataclass(frozen=True) +class ItemPoolMidSubmitTestCase: + description: str + start_second_thread: bool + expected_cancelled: tuple[str, ...] + expected_left_open: int diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/classes/helpers.py b/tests/unit/src/sqlbuild/executor/python_nodes/classes/helpers.py new file mode 100644 index 0000000000..a86656ae9d --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/python_nodes/classes/helpers.py @@ -0,0 +1,532 @@ +"""Discovered items that meet at barriers, run on either serial path.""" + +from __future__ import annotations + +import threading +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any, ClassVar, cast + +import pytest + +from sqlbuild._native import ( + CommandTerminated, + DiscoveredAssetFunction, + DiscoveredProjectInputs, + LocalConfig, + ProjectConfig, + PythonNodeGraph, + build_python_node_graph, +) +from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter +from sqlbuild.assets import AssetContext +from sqlbuild.compiler.python_nodes.types import SkipMode +from sqlbuild.executor.python_nodes._helpers.ingress_execution import ( + execute_ingress_python_loader_nodes, +) +from sqlbuild.executor.python_nodes.classes.read_side_python_execution_tracker import ( + ReadSidePythonExecutionTracker, +) +from sqlbuild.executor.python_nodes.models import ( + IngressCallbacks, + PythonNodeExecutionResult, + PythonNodeRuntime, +) +from sqlbuild.executor.scheduling.classes.lifecycle_progress import LifecycleProgress +from sqlbuild.python_nodes.models import DiscoveredItemRef + +WAIT_SECONDS: float = 30 + + +class ItemPoolTestAdapter(BaseAdapter): + """Counts the connections a run opens.""" + + adapter_name: ClassVar[str] = "item-pool-test" + + def __init__(self, *, adapter_name: str = "item-pool-test") -> None: + self.__dict__["adapter_name"] = adapter_name + self.connections: int = 0 + self.closed: int = 0 + + def connect(self, config: dict[str, object]) -> object: + del config + self.connections += 1 + return object() + + def close(self, connection: object) -> None: + del connection + self.closed += 1 + + def _execute(self, connection: Any, sql: str) -> object: + del connection + return sql + + +class ItemProbe: + """What the items saw: who ran at once, on which threads, after whose reports.""" + + def __init__(self, *, actions: dict[str, Callable[[], object]] | None = None) -> None: + self.actions: dict[str, Callable[[], object]] = actions or {} + self.reported: list[PythonNodeExecutionResult] = [] + self.report_threads: set[int] = set() + self.started: list[str] = [] + self.start_threads: set[int] = set() + self.started_before: dict[str, frozenset[str]] = {} + self.cancelled: list[str] = [] + self.seen_before: dict[str, frozenset[str]] = {} + self.threads: set[int] = set() + self.most_at_once: int = 0 + self.after_report: Callable[[str], None] = lambda name: None + self._active: int = 0 + self._lock: threading.Lock = threading.Lock() + + def step(self, name: str) -> object: + with self._lock: + self._active += 1 + self.most_at_once = max(self.most_at_once, self._active) + self.threads.add(threading.get_ident()) + self.started_before[name] = frozenset(self.started) + self.seen_before[name] = frozenset(result.node_name for result in self.reported) + try: + return self.actions.get(name, lambda: None)() + finally: + with self._lock: + self._active -= 1 + + def start(self, name: str) -> None: + self.start_threads.add(threading.get_ident()) + self.started.append(name) + + def report(self, result: object) -> None: + reported: PythonNodeExecutionResult = cast(PythonNodeExecutionResult, result) + self.report_threads.add(threading.get_ident()) + self.reported.append(reported) + self.after_report(reported.node_name) + + +def run_item(ctx: AssetContext) -> object: + """Run one item as its probe says.""" + + discovered: Any = cast(Any, ctx.discovered) + probe: ItemProbe = cast(ItemProbe, ctx.vars["probe"]) + outcome: object = probe.step(str(discovered.item)) + skips: dict[object, Callable[[], object]] = { + "soft": lambda: ctx.skip(reason="nothing to do", mode=SkipMode.SOFT), + "hard": lambda: ctx.skip(reason="cannot run", mode=SkipMode.HARD), + } + return skips.get(outcome, lambda: None)() + + +def fail_item() -> object: + """An item that raises.""" + + raise ValueError("the step failed") + + +def meet_at(barrier: threading.Barrier) -> object: + """An item that returns only once `barrier`'s other parties have arrived.""" + + _ = barrier.wait(timeout=WAIT_SECONDS) + return None + + +def item_refs(parents: tuple[str, ...]) -> Any: + """An item's dependencies on the items named `parents`.""" + + return tuple(map(_item_ref, parents)) + + +def _item_ref(name: str) -> DiscoveredItemRef: + return DiscoveredItemRef(name=name) + + +def item_graph( + items: tuple[tuple[str, str, int | None, tuple[str, ...]], ...], +) -> PythonNodeGraph: + """Nodes named by item, each `(name, set, max_parallel, parents)`.""" + + return build_python_node_graph( + discovered_inputs=DiscoveredProjectInputs( + project_config=ProjectConfig(name="demo", adapter="duckdb"), + local_config=LocalConfig(), + asset_functions=tuple( + DiscoveredAssetFunction( + file_path=Path("/project/python/plan.py"), + relative_path=Path("python/plan.py"), + name=name, + function=run_item, + depends_on=item_refs(parents), + discovered={ + "asset": "fulfil", + "set": set_name, + "item": name, + "args": {}, + "tags": {}, + "max_parallel": max_parallel, + "placeholder": False, + "error": None, + }, + ) + for name, set_name, max_parallel, parents in items + ), + ) + ) + + +def ignore_identity(*, identity: object, _target_name: str | None) -> None: + """Record no identity.""" + + del identity, _target_name + + +def item_runtime(*, adapter: ItemPoolTestAdapter, probe: ItemProbe) -> PythonNodeRuntime: + """A runtime that persists nothing.""" + + return PythonNodeRuntime( + adapter=adapter, + connection_config={}, + connection=object(), + run_id="test_run", + target="dev", + vars={"probe": probe}, + is_reload=False, + persist_node_results=False, + ) + + +def run_read_side( + *, graph: PythonNodeGraph, adapter: ItemPoolTestAdapter, probe: ItemProbe +) -> tuple[PythonNodeExecutionResult, ...]: + """Every node through the read-side tracker.""" + + tracker: ReadSidePythonExecutionTracker = ReadSidePythonExecutionTracker( + python_graph=graph, + selected_python_names=frozenset(graph.nodes_by_name), + scheduled_sql_names=frozenset(), + runtime=item_runtime(adapter=adapter, probe=probe), + identity_recorder=ignore_identity, + on_node_complete=probe.report, + on_asset_start=probe.start, + on_node_cancelled=probe.cancelled.append, + ) + tracker.dispatch_ready_python_nodes() + return tracker.results + + +def run_ingress( + *, graph: PythonNodeGraph, adapter: ItemPoolTestAdapter, probe: ItemProbe +) -> tuple[PythonNodeExecutionResult, ...]: + """Every node through the ingress lifecycle scheduler.""" + + return execute_ingress_python_loader_nodes( + python_graph=graph, + selected_python_names=frozenset(graph.nodes_by_name), + loader_functions=(), + source_map={}, + runtime=item_runtime(adapter=adapter, probe=probe), + callbacks=IngressCallbacks( + on_node_complete=probe.report, + on_asset_start=probe.start, + on_node_cancelled=probe.cancelled.append, + identity_recorder=ignore_identity, + ), + ).python_results + + +def result_summary( + results: tuple[PythonNodeExecutionResult, ...], +) -> frozenset[tuple[str, str, str | None, str | None]]: + """Each node's status and why, whatever order they finished in.""" + + return frozenset( + (result.node_name, result.status.value, result.error_message, result.skip_reason) + for result in results + ) + + +def write_step(ctx: AssetContext) -> object: + """Write a table and a result while every other step does.""" + + discovered: Any = cast(Any, ctx.discovered) + step: str = str(discovered.item) + barrier: threading.Barrier = cast(threading.Barrier, ctx.vars["barrier"]) + _ = barrier.wait(timeout=WAIT_SECONDS) + ctx.execute_sql(f"CREATE OR REPLACE TABLE main.step_{step} AS SELECT 1 AS written") + _ = barrier.wait(timeout=WAIT_SECONDS) + return ctx.result(payload={"step": step}) + + +def writing_graph(steps: tuple[str, ...]) -> PythonNodeGraph: + """Every step at once on one set.""" + + return build_python_node_graph( + discovered_inputs=DiscoveredProjectInputs( + project_config=ProjectConfig(name="demo", adapter="duckdb"), + local_config=LocalConfig(), + asset_functions=tuple( + DiscoveredAssetFunction( + file_path=Path("/project/python/plan.py"), + relative_path=Path("python/plan.py"), + name=step, + function=write_step, + discovered={ + "asset": "fulfil", + "set": "plan", + "item": step, + "args": {}, + "tags": {}, + "max_parallel": len(steps), + "placeholder": False, + "error": None, + }, + ) + for step in steps + ), + ) + ) + + +def run_writing_read_side( + *, graph: PythonNodeGraph, runtime: PythonNodeRuntime +) -> tuple[PythonNodeExecutionResult, ...]: + """Every writing step through the read-side tracker.""" + + tracker: ReadSidePythonExecutionTracker = ReadSidePythonExecutionTracker( + python_graph=graph, + selected_python_names=frozenset(graph.nodes_by_name), + scheduled_sql_names=frozenset(), + runtime=runtime, + ) + tracker.dispatch_ready_python_nodes() + return tracker.results + + +def run_writing_ingress( + *, graph: PythonNodeGraph, runtime: PythonNodeRuntime +) -> tuple[PythonNodeExecutionResult, ...]: + """Every writing step through the ingress lifecycle scheduler.""" + + return execute_ingress_python_loader_nodes( + python_graph=graph, + selected_python_names=frozenset(graph.nodes_by_name), + loader_functions=(), + source_map={}, + runtime=runtime, + ).python_results + + +def run_shape( + *, + run_path: Callable[..., tuple[PythonNodeExecutionResult, ...]], + shape: tuple[tuple[str, tuple[str, ...]], ...], + limit: int | None, + action: Callable[[], object], +) -> frozenset[tuple[str, str, str | None, str | None]]: + """How `shape`'s nodes end at `limit` when its first node takes `action`.""" + + return result_summary( + run_path( + graph=item_graph(tuple((name, "plan", limit, up) for name, up in shape)), + adapter=ItemPoolTestAdapter(), + probe=ItemProbe(actions={"a": action}), + ) + ) + + +def interrupted_probe() -> ItemProbe: + """`quick` finishes and its report raises an interrupt while `slow` is still running.""" + + both_running: threading.Barrier = threading.Barrier(2) + interrupted: threading.Event = threading.Event() + + def quick() -> object: + return meet_at(both_running) + + def slow() -> object: + _ = both_running.wait(timeout=WAIT_SECONDS) + assert interrupted.wait(timeout=WAIT_SECONDS) + return fail_item() + + probe: ItemProbe = ItemProbe(actions={"quick": quick, "slow": slow}) + + def interrupt(name: str) -> None: + probe.after_report = lambda reported: None + interrupted.set() + raise KeyboardInterrupt(name) + + probe.after_report = interrupt + return probe + + +def interrupt_after_next_record(monkeypatch: pytest.MonkeyPatch) -> None: + """Raise an interrupt once the next ingress result is recorded, as a signal can.""" + + record: Callable[..., None] = LifecycleProgress.complete + + def record_then_interrupt(progress: LifecycleProgress, **recorded: Any) -> None: + monkeypatch.setattr(LifecycleProgress, "complete", record) + record(progress, **recorded) + raise KeyboardInterrupt + + monkeypatch.setattr(LifecycleProgress, "complete", record_then_interrupt) + + +def ignoring_probe(release: threading.Event) -> ItemProbe: + """`quick` finishes and its report raises an interrupt; `slow` ignores it until released.""" + + both_running: threading.Barrier = threading.Barrier(2) + + def quick() -> object: + return meet_at(both_running) + + def slow() -> object: + _ = both_running.wait(timeout=WAIT_SECONDS) + _ = release.wait(timeout=WAIT_SECONDS) + return None + + probe: ItemProbe = ItemProbe(actions={"quick": quick, "slow": slow}) + + def interrupt(name: str) -> None: + probe.after_report = lambda reported: None + raise KeyboardInterrupt(name) + + probe.after_report = interrupt + return probe + + +def twice_cancelled_probe(items: tuple[str, ...]) -> ItemProbe: + """Items finish together; the cancel lands at the first report and its signal at the next.""" + + barrier: threading.Barrier = threading.Barrier(len(items)) + probe: ItemProbe = ItemProbe(actions={name: lambda: meet_at(barrier) for name in items}) + + def signalled(name: str) -> None: + probe.after_report = lambda reported: None + raise CommandTerminated(name) + + def cancelled(name: str) -> None: + probe.after_report = signalled + raise KeyboardInterrupt(name) + + probe.after_report = cancelled + return probe + + +class SlowResultAdapter(DuckDbAdapter): + """Writes `slow`'s result slowly, and fails that write when it is cancelled.""" + + def __init__(self, *, write_seconds: float) -> None: + super().__init__() + self.write_seconds: float = write_seconds + self.writing: threading.Event = threading.Event() + self.killed: threading.Event = threading.Event() + + def _execute(self, connection: Any, sql: str) -> object: + writes: dict[bool, Callable[[], None]] = {True: self._write_slowly, False: lambda: None} + writes["INSERT" in sql and "node_results" in sql and "'slow'" in sql]() + return super()._execute(connection=connection, sql=sql) + + def _write_slowly(self) -> None: + self.writing.set() + killed: bool = self.killed.wait(timeout=self.write_seconds) + self.writing.clear() + outcomes: dict[bool, Callable[[], object]] = {True: fail_item, False: lambda: None} + _ = outcomes[killed]() + + def interrupt_connection(self, connection: Any) -> bool: + del connection + marks: dict[bool, Callable[[], None]] = {True: self.killed.set, False: lambda: None} + marks[self.writing.is_set()]() + return True + + +def run_persisting_read_side( + *, graph: PythonNodeGraph, adapter: DuckDbAdapter, probe: ItemProbe, database: Path +) -> None: + """Every node through the read-side tracker, each result written to `database`.""" + + config: dict[str, object] = {"database": str(database)} + ReadSidePythonExecutionTracker( + python_graph=graph, + selected_python_names=frozenset(graph.nodes_by_name), + scheduled_sql_names=frozenset(), + runtime=PythonNodeRuntime( + adapter=adapter, + connection_config=config, + connection=adapter.connect(config), + run_id="test_run", + target="dev", + vars={"probe": probe}, + is_reload=False, + default_schema="main", + ), + identity_recorder=ignore_identity, + on_node_complete=probe.report, + on_node_cancelled=probe.cancelled.append, + ).dispatch_ready_python_nodes() + + +def finishing_probe() -> ItemProbe: + """`quick` finishes and its report raises an interrupt; `slow` finishes only after it.""" + + both_running: threading.Barrier = threading.Barrier(2) + interrupted: threading.Event = threading.Event() + + def quick() -> object: + return meet_at(both_running) + + def slow() -> object: + _ = both_running.wait(timeout=WAIT_SECONDS) + _ = interrupted.wait(timeout=WAIT_SECONDS) + return None + + probe: ItemProbe = ItemProbe(actions={"quick": quick, "slow": slow}) + + def interrupt(name: str) -> None: + probe.after_report = lambda reported: None + interrupted.set() + raise KeyboardInterrupt(name) + + probe.after_report = interrupt + return probe + + +def interrupt_second_submit( + monkeypatch: pytest.MonkeyPatch, *, start_thread: bool, started: threading.Event +) -> None: + """Raise an interrupt inside the second `submit`, after its thread starts or before it.""" + + adjust: Callable[[ThreadPoolExecutor], None] = ThreadPoolExecutor._adjust_thread_count + + def interrupted(executor: ThreadPoolExecutor) -> None: + threads: int = len(executor._threads) + outcomes: dict[bool, Callable[[], None]] = { + True: lambda: _interrupt_after(adjust, executor, start_thread, started), + False: lambda: adjust(executor), + } + outcomes[threads >= 1]() + + monkeypatch.setattr(ThreadPoolExecutor, "_adjust_thread_count", interrupted) + + +def _interrupt_after( + adjust: Callable[[ThreadPoolExecutor], None], + executor: ThreadPoolExecutor, + start_thread: bool, + started: threading.Event, +) -> None: + starts: dict[bool, Callable[[], object]] = { + True: lambda: (adjust(executor), started.wait(timeout=WAIT_SECONDS)), + False: lambda: None, + } + _ = starts[start_thread]() + raise KeyboardInterrupt("cancelled inside submit") + + +def held_until(release: threading.Event, started: threading.Event | None) -> object: + """An item that says it started, if asked, then ignores a cancel until released.""" + + _ = started is not None and started.set() + return release.wait(timeout=WAIT_SECONDS) diff --git a/tests/unit/src/sqlbuild/executor/python_nodes/classes/test_discovered_item_pool.py b/tests/unit/src/sqlbuild/executor/python_nodes/classes/test_discovered_item_pool.py new file mode 100644 index 0000000000..7f53fe53b5 --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/python_nodes/classes/test_discovered_item_pool.py @@ -0,0 +1,537 @@ +"""Discovered items with `max_parallel` run side by side on both serial paths.""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable +from functools import partial +from pathlib import Path + +import pytest + +from sqlbuild._native import PythonNodeGraph +from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter +from sqlbuild.executor.python_nodes.models import PythonNodeExecutionResult, PythonNodeRuntime +from tests.unit.src.sqlbuild.executor.python_nodes.classes._test_types import ( + ItemPoolCancelTestCase, + ItemPoolCapTestCase, + ItemPoolFailureTestCase, + ItemPoolIgnoredCancelTestCase, + ItemPoolMidSubmitTestCase, + ItemPoolOrderTestCase, + ItemPoolRecordedInterruptTestCase, + ItemPoolRepeatedCancelTestCase, + ItemPoolResultWriteTestCase, + ItemPoolSerialTestCase, + ItemPoolWriteTestCase, +) +from tests.unit.src.sqlbuild.executor.python_nodes.classes.helpers import ( + ItemPoolTestAdapter, + ItemProbe, + SlowResultAdapter, + fail_item, + finishing_probe, + held_until, + ignoring_probe, + interrupt_after_next_record, + interrupt_second_submit, + interrupted_probe, + item_graph, + meet_at, + run_ingress, + run_persisting_read_side, + run_read_side, + run_shape, + run_writing_ingress, + run_writing_read_side, + twice_cancelled_probe, + writing_graph, +) + +_PATHS: tuple[Callable[..., tuple[PythonNodeExecutionResult, ...]], ...] = ( + run_read_side, + run_ingress, +) + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolCapTestCase( + description="six items capped at two", + items=tuple((f"fulfil[{index}]", "plan", 2) for index in range(6)), + meet=2, + expected_connections=2, + expected_most_at_once=2, + ), + ItemPoolCapTestCase( + description="six items capped at three", + items=tuple((f"fulfil[{index}]", "plan", 3) for index in range(6)), + meet=3, + expected_connections=3, + expected_most_at_once=3, + ), + ItemPoolCapTestCase( + description="two assets on one set share the cap", + items=( + ("bill[0]", "plan", 2), + ("bill[1]", "plan", 2), + ("bill[2]", "plan", 2), + ("fulfil[0]", "plan", 2), + ("fulfil[1]", "plan", 2), + ("fulfil[2]", "plan", 2), + ), + meet=2, + expected_connections=2, + expected_most_at_once=2, + ), + ItemPoolCapTestCase( + description="two sets each have their own cap", + items=( + ("bill[0]", "billing", 2), + ("bill[1]", "billing", 2), + ("fulfil[0]", "plan", 3), + ("fulfil[1]", "plan", 3), + ("fulfil[2]", "plan", 3), + ), + meet=5, + expected_connections=5, + expected_most_at_once=5, + ), + ], + ids=lambda case: case.description, +) +def test_given_ready_items_when_running_then_the_cap_is_reached_and_never_exceeded( + test_case: ItemPoolCapTestCase, +) -> None: + for run_path in _PATHS: + barrier: threading.Barrier = threading.Barrier(test_case.meet) + probe: ItemProbe = ItemProbe( + actions={name: partial(meet_at, barrier) for name, _, _ in test_case.items} + ) + adapter: ItemPoolTestAdapter = ItemPoolTestAdapter() + graph: PythonNodeGraph = item_graph( + tuple((name, set_name, limit, ()) for name, set_name, limit in test_case.items) + ) + + results: tuple[PythonNodeExecutionResult, ...] = run_path( + graph=graph, adapter=adapter, probe=probe + ) + + assert [result.error_message for result in results] == [None] * len(test_case.items) + assert (adapter.connections, probe.most_at_once) == ( + test_case.expected_connections, + test_case.expected_most_at_once, + ) + assert adapter.closed == adapter.connections + assert probe.report_threads == {threading.get_ident()} + assert probe.start_threads == {threading.get_ident()} + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolOrderTestCase( + description="a diamond runs its middle together and its ends alone", + items=( + ("a", 4, ()), + ("b", 4, ("a",)), + ("c", 4, ("a",)), + ("d", 4, ("b", "c")), + ), + meeting=("b", "c"), + expected_seen_before={ + "a": frozenset(), + "b": frozenset({"a"}), + "c": frozenset({"a"}), + "d": frozenset({"a", "b", "c"}), + }, + ), + ItemPoolOrderTestCase( + description="an unset set runs serially beside a parallel one's dependencies", + items=(("a", None, ()), ("b", 2, ("a",)), ("c", 2, ("a",)), ("d", None, ("b", "c"))), + meeting=("b", "c"), + expected_seen_before={ + "a": frozenset(), + "b": frozenset({"a"}), + "c": frozenset({"a"}), + "d": frozenset({"a", "b", "c"}), + }, + ), + ], + ids=lambda case: case.description, +) +def test_given_dependencies_when_running_then_an_item_starts_after_its_parents_are_reported( + test_case: ItemPoolOrderTestCase, +) -> None: + for run_path in _PATHS: + barrier: threading.Barrier = threading.Barrier(len(test_case.meeting)) + probe: ItemProbe = ItemProbe( + actions={name: partial(meet_at, barrier) for name in test_case.meeting} + ) + graph: PythonNodeGraph = item_graph( + tuple( + (name, f"set-{limit}", limit, parents) for name, limit, parents in test_case.items + ) + ) + + _ = run_path(graph=graph, adapter=ItemPoolTestAdapter(), probe=probe) + + assert probe.seen_before == test_case.expected_seen_before + assert {name: name in before for name, before in probe.started_before.items()} == ( + dict.fromkeys(test_case.expected_seen_before, True) + ) + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolSerialTestCase( + description="unset is serial", + max_parallel=None, + adapter_name="item-pool-test", + expected_threads=1, + expected_connections=0, + ), + ItemPoolSerialTestCase( + description="one is serial", + max_parallel=1, + adapter_name="item-pool-test", + expected_threads=1, + expected_connections=0, + ), + ItemPoolSerialTestCase( + description="a database private to its connection stays serial", + max_parallel=4, + adapter_name="duckdb", + expected_threads=1, + expected_connections=0, + ), + ], + ids=lambda case: case.description, +) +def test_given_no_parallelism_when_running_then_items_run_one_by_one_on_the_calling_thread( + test_case: ItemPoolSerialTestCase, +) -> None: + for run_path in _PATHS: + probe: ItemProbe = ItemProbe() + adapter: ItemPoolTestAdapter = ItemPoolTestAdapter(adapter_name=test_case.adapter_name) + graph: PythonNodeGraph = item_graph( + tuple((name, "plan", test_case.max_parallel, ()) for name in ("a", "b", "c")) + ) + + _ = run_path(graph=graph, adapter=adapter, probe=probe) + + assert probe.threads == {threading.get_ident()} + assert (len(probe.threads), adapter.connections, probe.most_at_once) == ( + test_case.expected_threads, + test_case.expected_connections, + 1, + ) + assert probe.seen_before["c"] == frozenset({"a", "b"}) + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolFailureTestCase("a failure", "fail", "failed"), + ItemPoolFailureTestCase("a hard skip", "hard", "skipped"), + ItemPoolFailureTestCase("a soft skip", "soft", "skipped"), + ], + ids=lambda case: case.description, +) +def test_given_an_item_that_does_not_succeed_when_running_then_dependants_end_as_in_serial( + test_case: ItemPoolFailureTestCase, +) -> None: + for run_path in _PATHS: + outcomes: dict[str, Callable[[], object]] = { + "fail": fail_item, + "hard": lambda: "hard", + "soft": lambda: "soft", + } + shape: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("a", ()), + ("b", ("a",)), + ("c", ("b",)), + ("d", ()), + ("e", ("a", "d")), + ) + action: Callable[[], object] = outcomes[test_case.outcome] + serial: frozenset[tuple[str, str, str | None, str | None]] = run_shape( + run_path=run_path, shape=shape, limit=None, action=action + ) + parallel: frozenset[tuple[str, str, str | None, str | None]] = run_shape( + run_path=run_path, shape=shape, limit=3, action=action + ) + + assert parallel == serial + assert {row[0]: row[1] for row in parallel}["a"] == test_case.expected_first_status + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolCancelTestCase( + description="an interrupt with one step finished and one running", + expected_reported=frozenset({("quick", "success")}), + expected_cancelled=("slow",), + expected_never_started="waiting", + ) + ], + ids=lambda case: case.description, +) +def test_given_steps_in_flight_when_interrupted_then_finished_stay_succeeded_and_nothing_starts( + test_case: ItemPoolCancelTestCase, +) -> None: + for run_path in _PATHS: + probe: ItemProbe = interrupted_probe() + adapter: ItemPoolTestAdapter = ItemPoolTestAdapter() + graph: PythonNodeGraph = item_graph( + (("quick", "plan", 2, ()), ("slow", "plan", 2, ()), ("waiting", "plan", 2, ("quick",))) + ) + + with pytest.raises(KeyboardInterrupt): + _ = run_path(graph=graph, adapter=adapter, probe=probe) + + reported: frozenset[tuple[str, str]] = frozenset( + (result.node_name, result.status.value) for result in probe.reported + ) + assert (reported, tuple(probe.cancelled)) == ( + test_case.expected_reported, + test_case.expected_cancelled, + ) + assert test_case.expected_never_started not in probe.seen_before + assert adapter.closed == adapter.connections + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolWriteTestCase( + description="four steps create the result table and write at once", + steps=("label", "pack", "pick", "ship"), + expected_status="success", + ) + ], + ids=lambda case: case.description, +) +def test_given_concurrent_steps_using_sql_when_they_write_results_then_they_do_not_collide( + test_case: ItemPoolWriteTestCase, + tmp_path: Path, +) -> None: + for run_path in (run_writing_read_side, run_writing_ingress): + adapter: DuckDbAdapter = DuckDbAdapter() + config: dict[str, object] = {"database": str(tmp_path / f"{run_path.__name__}.duckdb")} + connection: object = adapter.connect(config) + runtime: PythonNodeRuntime = PythonNodeRuntime( + adapter=adapter, + connection_config=config, + connection=connection, + run_id="test_run", + target="dev", + vars={"barrier": threading.Barrier(len(test_case.steps))}, + is_reload=False, + default_schema="plan_state", + ) + + results: tuple[PythonNodeExecutionResult, ...] = run_path( + graph=writing_graph(test_case.steps), runtime=runtime + ) + + assert { + (result.node_name, result.status.value, result.error_message) for result in results + } == {(step, test_case.expected_status, None) for step in test_case.steps} + found: object = adapter.query( + connection=connection, + sql="SELECT table_name FROM information_schema.columns " + "WHERE table_schema = 'plan_state' AND column_name = 'payload_json_b64'", + limit=None, + ).rows[0][0] + table: str = str(found) + written: set[object] = { + row[0] + for row in adapter.query( + connection=connection, sql=f"SELECT node_name FROM plan_state.{table}", limit=None + ).rows + } + adapter.close(connection) + assert written == set(test_case.steps) + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolRecordedInterruptTestCase( + description="two steps running when the interrupt follows the first's record", + items=("bill", "pack"), + expected_reported=frozenset({("bill", "success"), ("pack", "success")}), + ) + ], + ids=lambda case: case.description, +) +def test_given_an_interrupt_just_after_a_record_when_running_then_it_still_ends_as_a_cancel( + test_case: ItemPoolRecordedInterruptTestCase, monkeypatch: pytest.MonkeyPatch +) -> None: + barrier: threading.Barrier = threading.Barrier(len(test_case.items)) + probe: ItemProbe = ItemProbe( + actions={name: partial(meet_at, barrier) for name in test_case.items} + ) + graph: PythonNodeGraph = item_graph( + tuple((name, "plan", len(test_case.items), ()) for name in test_case.items) + ) + interrupt_after_next_record(monkeypatch) + + with pytest.raises(KeyboardInterrupt): + _ = run_ingress(graph=graph, adapter=ItemPoolTestAdapter(), probe=probe) + + reported: frozenset[tuple[str, str]] = frozenset( + (result.node_name, result.status.value) for result in probe.reported + ) + assert reported == test_case.expected_reported + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolIgnoredCancelTestCase( + description="one step ignores the cancel", + expected_reported=frozenset({("quick", "success")}), + expected_cancelled=("slow",), + expected_left_open=1, + expected_within_seconds=9, + ) + ], + ids=lambda case: case.description, +) +def test_given_a_step_ignoring_cancel_when_interrupted_then_it_is_reported_cancelled_and_not_joined( + test_case: ItemPoolIgnoredCancelTestCase, +) -> None: + for run_path in _PATHS: + release: threading.Event = threading.Event() + probe: ItemProbe = ignoring_probe(release) + adapter: ItemPoolTestAdapter = ItemPoolTestAdapter() + graph: PythonNodeGraph = item_graph((("quick", "plan", 2, ()), ("slow", "plan", 2, ()))) + + interrupted: float = time.monotonic() + with pytest.raises(KeyboardInterrupt): + _ = run_path(graph=graph, adapter=adapter, probe=probe) + waited: float = time.monotonic() - interrupted + release.set() + + reported: frozenset[tuple[str, str]] = frozenset( + (result.node_name, result.status.value) for result in probe.reported + ) + assert (reported, tuple(probe.cancelled)) == ( + test_case.expected_reported, + test_case.expected_cancelled, + ) + assert waited < test_case.expected_within_seconds + assert adapter.connections - adapter.closed == test_case.expected_left_open + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolRepeatedCancelTestCase( + description="the cancel's signal arrives while finished steps are reported", + items=("bill", "pack", "pick"), + expected_reported=frozenset( + {("bill", "success"), ("pack", "success"), ("pick", "success")} + ), + ) + ], + ids=lambda case: case.description, +) +def test_given_a_cancel_arriving_again_when_reporting_then_every_finished_step_is_still_reported( + test_case: ItemPoolRepeatedCancelTestCase, +) -> None: + for run_path in _PATHS: + probe: ItemProbe = twice_cancelled_probe(test_case.items) + graph: PythonNodeGraph = item_graph( + tuple((name, "plan", len(test_case.items), ()) for name in test_case.items) + ) + + with pytest.raises(KeyboardInterrupt): + _ = run_path(graph=graph, adapter=ItemPoolTestAdapter(), probe=probe) + + reported: frozenset[tuple[str, str]] = frozenset( + (result.node_name, result.status.value) for result in probe.reported + ) + assert (reported, probe.cancelled) == (test_case.expected_reported, []) + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolResultWriteTestCase( + description="a finished step's result write spans a cancel round", + write_seconds=2.5, + expected_reported=frozenset({("quick", "success"), ("slow", "success")}), + ) + ], + ids=lambda case: case.description, +) +def test_given_a_step_writing_its_result_when_a_cancel_round_passes_then_the_write_is_not_cancelled( + test_case: ItemPoolResultWriteTestCase, tmp_path: Path +) -> None: + probe: ItemProbe = finishing_probe() + graph: PythonNodeGraph = item_graph((("quick", "plan", 2, ()), ("slow", "plan", 2, ()))) + adapter: SlowResultAdapter = SlowResultAdapter(write_seconds=test_case.write_seconds) + + with pytest.raises(KeyboardInterrupt): + run_persisting_read_side( + graph=graph, adapter=adapter, probe=probe, database=tmp_path / "plan.duckdb" + ) + + reported: frozenset[tuple[str, str]] = frozenset( + (result.node_name, result.status.value) for result in probe.reported + ) + assert (reported, probe.cancelled) == (test_case.expected_reported, []) + + +@pytest.mark.parametrize( + "test_case", + [ + ItemPoolMidSubmitTestCase( + description="the second step started before the interrupt left submit", + start_second_thread=True, + expected_cancelled=("pack", "pick"), + expected_left_open=2, + ), + ItemPoolMidSubmitTestCase( + description="the second step never started", + start_second_thread=False, + expected_cancelled=("pick", "pack"), + expected_left_open=1, + ), + ], + ids=lambda case: case.description, +) +def test_given_an_interrupt_inside_a_submit_when_cancelling_then_the_step_is_tracked_and_reported( + test_case: ItemPoolMidSubmitTestCase, monkeypatch: pytest.MonkeyPatch +) -> None: + for run_path in _PATHS: + release: threading.Event = threading.Event() + started: threading.Event = threading.Event() + probe: ItemProbe = ItemProbe( + actions={ + "pack": partial(held_until, release, None), + "pick": partial(held_until, release, started), + } + ) + adapter: ItemPoolTestAdapter = ItemPoolTestAdapter() + graph: PythonNodeGraph = item_graph((("pack", "plan", 2, ()), ("pick", "plan", 2, ()))) + interrupt_second_submit( + monkeypatch, start_thread=test_case.start_second_thread, started=started + ) + + began: float = time.monotonic() + with pytest.raises(KeyboardInterrupt): + _ = run_path(graph=graph, adapter=adapter, probe=probe) + waited: float = time.monotonic() - began + release.set() + + assert (tuple(probe.cancelled), probe.reported) == (test_case.expected_cancelled, []) + assert waited < 9 + assert adapter.connections - adapter.closed == test_case.expected_left_open diff --git a/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py b/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py index 970a227712..ef1cf4065b 100644 --- a/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py +++ b/tests/unit/src/sqlbuild/executor/run/_helpers/test_hooks.py @@ -219,7 +219,7 @@ def notify(ctx: HookContext, message: str) -> None: observed_cost_contexts.append(CostContext.current()) ctx.execute_sql("CREATE TABLE hook_log AS SELECT 1 AS value") rows: list[tuple[object, ...]] = ctx.query("SELECT value FROM hook_log") - ctx.log(message) + ctx.log.info(message) captured.append((ctx, message, rows)) with CostContext.scope( diff --git a/tests/unit/src/sqlbuild/executor/shared/_helpers/test_statement_recorder.py b/tests/unit/src/sqlbuild/executor/shared/_helpers/test_statement_recorder.py index 4656b3a53b..4bce4227a2 100644 --- a/tests/unit/src/sqlbuild/executor/shared/_helpers/test_statement_recorder.py +++ b/tests/unit/src/sqlbuild/executor/shared/_helpers/test_statement_recorder.py @@ -37,7 +37,7 @@ def test_given_recorded_events_when_snapshotting_then_returns_expected_tuple( recorder: StatementRecorder = StatementRecorder() recorder.record(test_case.statements[0]) - recorder.log(test_case.log_message) + recorder.log(message=test_case.log_message) recorder.record_many(test_case.statements[1:]) result: tuple[LifeCycleEvent, ...] = recorder.snapshot() diff --git a/tests/unit/src/sqlbuild/provider/classes/_test_types.py b/tests/unit/src/sqlbuild/provider/classes/_test_types.py index b22e30cea9..57556e3afb 100644 --- a/tests/unit/src/sqlbuild/provider/classes/_test_types.py +++ b/tests/unit/src/sqlbuild/provider/classes/_test_types.py @@ -2,7 +2,12 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from sqlbuild.provider.classes.session import ProviderSession @dataclass(frozen=True) @@ -34,3 +39,11 @@ class ProviderSessionErrorTestCase: description: str provider_name: str expected_error_fragment: str + + +@dataclass(frozen=True) +class ProviderSessionLeftOpenTestCase: + description: str + closes: tuple[Callable[[ProviderSession], None], ...] + within_seconds: float + expected_events: tuple[str, ...] diff --git a/tests/unit/src/sqlbuild/provider/classes/test_session.py b/tests/unit/src/sqlbuild/provider/classes/test_session.py index adb3856c01..accbd512ed 100644 --- a/tests/unit/src/sqlbuild/provider/classes/test_session.py +++ b/tests/unit/src/sqlbuild/provider/classes/test_session.py @@ -1,8 +1,10 @@ from __future__ import annotations import re +import time from concurrent.futures import ThreadPoolExecutor -from threading import Barrier +from functools import partial +from threading import Barrier, Event, Thread from typing import ClassVar import pytest @@ -18,6 +20,7 @@ ProviderContainerLookupTestCase, ProviderContainerMissingTestCase, ProviderSessionErrorTestCase, + ProviderSessionLeftOpenTestCase, ProviderSessionLifecycleTestCase, ) @@ -77,6 +80,22 @@ def teardown(self) -> None: self.__class__.teardown_calls += 1 +class HeldSetupProvider(Provider): + provider_name: ClassVar[str] = "held_setup" + started: ClassVar[Event] = Event() + release: ClassVar[Event] = Event() + events: ClassVar[list[str]] = [] + label: str + + def setup(self, ctx: object) -> None: + self.events.append(f"setup:{self.label}") + self.started.set() + _ = self.release.wait(timeout=30) + + def teardown(self) -> None: + self.events.append(f"teardown:{self.label}") + + @pytest.mark.parametrize( "test_case", [ @@ -542,3 +561,62 @@ def test_given_teardown_failure_when_execution_already_failed_then_original_erro assert session.teardown_error is not None assert test_case.expected_error_fragment in str(session.teardown_error) + + +@pytest.mark.parametrize( + "test_case", + [ + ProviderSessionLeftOpenTestCase( + description="a setup still running when providers are left open and closed", + closes=(ProviderSession.close,), + within_seconds=1, + expected_events=("setup:gateway",), + ), + ProviderSessionLeftOpenTestCase( + description="a sink's hold released and its forced close, as a sink closes", + closes=(ProviderSession.release, partial(ProviderSession.close, force=True)), + within_seconds=1, + expected_events=("setup:gateway",), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_running_setup_when_left_open_and_closed_then_neither_waits_and_no_setup_follows( + test_case: ProviderSessionLeftOpenTestCase, +) -> None: + HeldSetupProvider.started = Event() + HeldSetupProvider.release = Event() + HeldSetupProvider.events = [] + session: ProviderSession = ProviderSession( + { + "gateway": HeldSetupProvider(label="gateway"), + "archive": HeldSetupProvider(label="archive"), + } + ) + lookups: list[str] = [] + + def look_up(name: str) -> None: + try: + _ = session.providers[name] + lookups.append(f"{name}:found") + except ProviderLookupError: + lookups.append(f"{name}:closed") + + setting_up: Thread = Thread(target=look_up, args=("gateway",), daemon=True) + setting_up.start() + assert HeldSetupProvider.started.wait(timeout=5) + waiting: Thread = Thread(target=look_up, args=("archive",), daemon=True) + waiting.start() + + began: float = time.monotonic() + session.providers.leave_open() + for close in test_case.closes: + close(session) + took: float = time.monotonic() - began + HeldSetupProvider.release.set() + setting_up.join(timeout=5) + waiting.join(timeout=5) + + assert took < test_case.within_seconds + assert tuple(HeldSetupProvider.events) == test_case.expected_events + assert sorted(lookups) == ["archive:closed", "gateway:found"] diff --git a/tests/unit/src/sqlbuild/python_nodes/main/_test_types.py b/tests/unit/src/sqlbuild/python_nodes/main/_test_types.py index b38ab648a9..fdeadd0f32 100644 --- a/tests/unit/src/sqlbuild/python_nodes/main/_test_types.py +++ b/tests/unit/src/sqlbuild/python_nodes/main/_test_types.py @@ -3,7 +3,7 @@ from dataclasses import dataclass from sqlbuild.compiler.auditing.types import ThresholdOperator -from sqlbuild.python_nodes.models import RetryPolicy +from sqlbuild.python_nodes.models import DiscoverDefinition, Item, RetryPolicy @dataclass(frozen=True) @@ -58,3 +58,30 @@ class JitteredRetryDelayTestCase: retry_index: int seed: int expected_upper_bound: float + + +@dataclass(frozen=True) +class DiscoveredResultTestCase: + description: str + items: tuple[Item, ...] + expected_items: list[dict[str, object]] + + +@dataclass(frozen=True) +class DiscoveredArgsErrorTestCase: + description: str + args: dict[str, object] + expected_error_fragment: str + + +@dataclass(frozen=True) +class DiscoverAuthoringErrorTestCase: + description: str + expected_error_fragment: str + + +@dataclass(frozen=True) +class DiscoverDefinitionTestCase: + description: str + expected_definition: DiscoverDefinition + expected_for_each: str diff --git a/tests/unit/src/sqlbuild/python_nodes/main/helpers.py b/tests/unit/src/sqlbuild/python_nodes/main/helpers.py new file mode 100644 index 0000000000..97ef4a5417 --- /dev/null +++ b/tests/unit/src/sqlbuild/python_nodes/main/helpers.py @@ -0,0 +1,18 @@ +"""Authored discover and asset functions the discovered-result tests check items against.""" + +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, discover + + +@discover(check_every="15m") +def orders_plan() -> Discovered: + return Discovered(items=()) + + +@asset(for_each=orders_plan) +def step(ctx: AssetContext, step_id: str, retries: int = 1, warehouse: object = None) -> None: + del ctx, step_id, retries, warehouse + + +def not_discovered() -> None: + return None diff --git a/tests/unit/src/sqlbuild/python_nodes/main/test_discovered_result_json.py b/tests/unit/src/sqlbuild/python_nodes/main/test_discovered_result_json.py new file mode 100644 index 0000000000..e2e972e0dd --- /dev/null +++ b/tests/unit/src/sqlbuild/python_nodes/main/test_discovered_result_json.py @@ -0,0 +1,156 @@ +import json + +import pytest + +from sqlbuild._native import PythonNodeDiscoveryError +from sqlbuild.assets import asset +from sqlbuild.discovery import Discovered, Item, get_discover_definition +from sqlbuild.python_nodes.main.discovered_result_json import discovered_result_json +from sqlbuild.python_nodes.main.read_asset_definition import read_asset_definition +from sqlbuild.python_nodes.models import AssetDefinition, DiscoverDefinition +from sqlbuild.refs import model, tag +from tests.unit.src.sqlbuild.python_nodes.main._test_types import ( + DiscoverAuthoringErrorTestCase, + DiscoverDefinitionTestCase, + DiscoveredArgsErrorTestCase, + DiscoveredResultTestCase, +) +from tests.unit.src.sqlbuild.python_nodes.main.helpers import not_discovered, orders_plan, step + +PROVIDERS: frozenset[str] = frozenset({"warehouse"}) + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoveredResultTestCase( + description="item IDs, model and tag dependencies and args become JSON", + items=( + Item(id="load", args={"step_id": "a"}), + Item( + id="fit", + depends_on=("load", model("orders"), tag("daily", exclude="slow")), + args={"step_id": "b", "retries": 3}, + ), + ), + expected_items=[ + {"id": "load", "depends_on": [], "args": {"step_id": "a"}}, + { + "id": "fit", + "depends_on": [ + {"item": "load"}, + {"model": "orders"}, + {"tag": {"name": "daily", "exclude": "slow"}}, + ], + "args": {"step_id": "b", "retries": 3}, + }, + ], + ), + ], + ids=lambda case: case.description, +) +def test_given_discovered_items_when_serialising_then_dependencies_and_args_keep_their_kinds( + test_case: DiscoveredResultTestCase, +) -> None: + returned: Discovered = Discovered(items=test_case.items, tags={"release": "r1"}, max_parallel=2) + + payload: object = json.loads( + discovered_result_json(returned=returned, functions=(step,), provider_names=PROVIDERS) + ) + + assert payload == { + "items": test_case.expected_items, + "tags": {"release": "r1"}, + "max_parallel": 2, + } + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoveredArgsErrorTestCase( + description="an unknown key is refused", + args={"step_id": "a", "speed": 2}, + expected_error_fragment="item 'x': step has no parameter speed", + ), + DiscoveredArgsErrorTestCase( + description="a parameter without a default must be supplied", + args={"retries": 2}, + expected_error_fragment="item 'x': args leave step's step_id unset", + ), + DiscoveredArgsErrorTestCase( + description="a provider parameter cannot be supplied", + args={"step_id": "a", "warehouse": "x"}, + expected_error_fragment="item 'x': step has no parameter warehouse", + ), + ], + ids=lambda case: case.description, +) +def test_given_args_that_do_not_fit_the_asset_when_serialising_then_the_set_fails( + test_case: DiscoveredArgsErrorTestCase, +) -> None: + returned: Discovered = Discovered(items=(Item(id="x", args=test_case.args),)) + + with pytest.raises(PythonNodeDiscoveryError, match=test_case.expected_error_fragment): + discovered_result_json(returned=returned, functions=(step,), provider_names=PROVIDERS) + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoverDefinitionTestCase( + description="the asset names its discover function's set", + expected_definition=DiscoverDefinition(name="orders_plan", check_every="15m"), + expected_for_each="orders_plan", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_discover_function_when_reading_definitions_then_the_asset_names_its_set( + test_case: DiscoverDefinitionTestCase, +) -> None: + discover_definition: DiscoverDefinition | None = get_discover_definition(orders_plan) + asset_definition: AssetDefinition | None = read_asset_definition(step) + + assert (discover_definition, asset_definition and asset_definition.for_each) == ( + test_case.expected_definition, + test_case.expected_for_each, + ) + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoverAuthoringErrorTestCase( + description="for_each refuses a function that is not a discover function", + expected_error_fragment="for_each takes a function decorated with @discover", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_plain_function_when_used_as_for_each_then_the_decorator_refuses_it( + test_case: DiscoverAuthoringErrorTestCase, +) -> None: + with pytest.raises(PythonNodeDiscoveryError, match=test_case.expected_error_fragment): + asset(for_each=not_discovered) + + +@pytest.mark.parametrize( + "test_case", + [ + DiscoverAuthoringErrorTestCase( + description="a list is not a Discovered", + expected_error_fragment="must return Discovered", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_return_value_that_is_not_discovered_when_serialising_then_it_names_the_type( + test_case: DiscoverAuthoringErrorTestCase, +) -> None: + with pytest.raises(PythonNodeDiscoveryError, match=test_case.expected_error_fragment): + discovered_result_json(returned=[], functions=(), provider_names=frozenset()) + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/runtime/execution_limits/_test_types.py b/tests/unit/src/sqlbuild/runtime/execution_limits/_test_types.py index fc2c0e24df..5b05439252 100644 --- a/tests/unit/src/sqlbuild/runtime/execution_limits/_test_types.py +++ b/tests/unit/src/sqlbuild/runtime/execution_limits/_test_types.py @@ -1,4 +1,5 @@ from collections.abc import Callable +from contextlib import AbstractContextManager from dataclasses import dataclass from sqlbuild.runtime.execution_limits.models import ItemTimeoutPolicy @@ -93,3 +94,25 @@ class InterruptedConnectionReportsTestCase: class InterruptedIdentityReuseTestCase: description: str expected_reuse_and_report: tuple[bool, bool] + + +@dataclass(frozen=True) +class BookkeepingCancelTestCase: + description: str + marking: Callable[[], AbstractContextManager[None]] + expected_cancelled: bool + + +@dataclass(frozen=True) +class BookkeepingActivityTestCase: + description: str + marking: Callable[[], AbstractContextManager[None]] + expected_activity_during: tuple[bool, bool] + expected_activity_after: tuple[bool, bool] + expected_cancelled: bool + + +@dataclass(frozen=True) +class BookkeepingDeadlineTestCase: + description: str + expected_expired: bool diff --git a/tests/unit/src/sqlbuild/runtime/execution_limits/test_bookkeeping_statements.py b/tests/unit/src/sqlbuild/runtime/execution_limits/test_bookkeeping_statements.py new file mode 100644 index 0000000000..a9f28dc0c7 --- /dev/null +++ b/tests/unit/src/sqlbuild/runtime/execution_limits/test_bookkeeping_statements.py @@ -0,0 +1,137 @@ +"""A node's bookkeeping writes escape cancels and terminations, but not its deadline.""" + +from __future__ import annotations + +import contextlib +import importlib + +import pytest + +from sqlbuild.runtime.execution_limits.classes.active_connections import ActiveConnections +from sqlbuild.runtime.execution_limits.classes.item_deadline import ItemDeadline +from sqlbuild.runtime.execution_limits.main.bookkeeping_statements import bookkeeping_statements +from sqlbuild.runtime.execution_limits.main.cancel_running_statements import ( + cancel_running_statements, +) +from sqlbuild.runtime.execution_limits.main.item_deadline_scope import item_deadline_scope +from sqlbuild.runtime.execution_limits.main.statement_activity import statement_activity +from sqlbuild.runtime.execution_limits.main.tracked_statement_connection import ( + tracked_statement_connection, +) +from sqlbuild.runtime.execution_limits.models import ItemTimeoutPolicy +from sqlbuild.runtime.execution_limits.types import ItemKind +from tests.unit.src.sqlbuild.runtime.execution_limits._test_types import ( + BookkeepingActivityTestCase, + BookkeepingCancelTestCase, + BookkeepingDeadlineTestCase, +) +from tests.unit.src.sqlbuild.runtime.execution_limits.helpers import ( + FakeCancellingAdapter, + run_statement_until_cancelled, +) + +_ONE_SECOND: ItemTimeoutPolicy = ItemTimeoutPolicy(limit="1s", seconds=1, source="test") +# Every module that reads the process-wide registry, so a test can give them a fresh one. +_REGISTRY_READERS: tuple[str, ...] = ( + "sqlbuild.runtime.execution_limits.main.tracked_statement_connection", + "sqlbuild.runtime.execution_limits.main.cancel_running_statements", + "sqlbuild.runtime.execution_limits.main.statement_activity", +) + + +@pytest.mark.parametrize( + "test_case", + [ + BookkeepingCancelTestCase( + description="a running step's statement is cancelled", + marking=contextlib.nullcontext, + expected_cancelled=True, + ), + BookkeepingCancelTestCase( + description="a finished step's result or identity write is not", + marking=bookkeeping_statements, + expected_cancelled=False, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_running_statement_when_running_statements_are_cancelled_then_bookkeeping_is_left( + test_case: BookkeepingCancelTestCase, +) -> None: + adapter: FakeCancellingAdapter = FakeCancellingAdapter(result=True, asynchronous=False) + with test_case.marking(), tracked_statement_connection(adapter=adapter, connection=object()): + cancel_running_statements() + + assert adapter.interrupted.is_set() == test_case.expected_cancelled + + +@pytest.mark.parametrize( + "test_case", + [ + BookkeepingDeadlineTestCase( + description="a result write past its item's limit", + expected_expired=True, + ) + ], + ids=lambda case: case.description, +) +def test_given_a_bookkeeping_statement_when_its_item_deadline_expires_then_it_is_still_cancelled( + test_case: BookkeepingDeadlineTestCase, +) -> None: + adapter: FakeCancellingAdapter = FakeCancellingAdapter(result=True, asynchronous=False) + + with ( + item_deadline_scope( + kind=ItemKind.TEST, + name="orders_rollup", + policy=_ONE_SECOND, + adapter=adapter, + connection=None, + ) as deadline, + bookkeeping_statements(), + ): + run_statement_until_cancelled(adapter=adapter, finished_query_id=None) + + assert isinstance(deadline, ItemDeadline) + assert deadline.expired == test_case.expected_expired + + +@pytest.mark.parametrize( + "test_case", + [ + BookkeepingActivityTestCase( + description="a finished step's result or identity write counts as run, not as running", + marking=bookkeeping_statements, + expected_activity_during=(True, False), + expected_activity_after=(True, False), + expected_cancelled=False, + ), + BookkeepingActivityTestCase( + description="a running step's statement counts as run and as running", + marking=contextlib.nullcontext, + expected_activity_during=(True, True), + expected_activity_after=(True, False), + expected_cancelled=True, + ), + ], + ids=lambda case: case.description, +) +def test_given_only_a_bookkeeping_write_when_ctrl_c_reads_activity_then_a_statement_has_run( + test_case: BookkeepingActivityTestCase, monkeypatch: pytest.MonkeyPatch +) -> None: + registry: ActiveConnections = ActiveConnections() + for module in _REGISTRY_READERS: + monkeypatch.setattr(importlib.import_module(module), "running_statements", registry) + adapter: FakeCancellingAdapter = FakeCancellingAdapter(result=True, asynchronous=False) + before: tuple[bool, bool] = statement_activity() + + with test_case.marking(), tracked_statement_connection(adapter=adapter, connection=object()): + during: tuple[bool, bool] = statement_activity() + cancel_running_statements() + + assert (before, during, statement_activity(), adapter.interrupted.is_set()) == ( + (False, False), + test_case.expected_activity_during, + test_case.expected_activity_after, + test_case.expected_cancelled, + ) diff --git a/ui/e2e/people-roles.spec.ts b/ui/e2e/people-roles.spec.ts index e7d55959ab..e7715771d7 100644 --- a/ui/e2e/people-roles.spec.ts +++ b/ui/e2e/people-roles.spec.ts @@ -9,6 +9,15 @@ const row = (page: Page, name: string) => const roleOf = (page: Page, name: string) => row(page, name).getByTestId("role-select"); +/** Opens a role menu and picks `role`; labels may add "(default)". */ +async function pickRole(page: Page, trigger: ReturnType, role: string) { + await trigger.click(); + await page.getByRole("menuitemradio", { name: new RegExp(`^${role}`) }).click(); +} +const roleOption = (page: Page, role: string) => + page.getByRole("menuitemradio", { name: new RegExp(`^${role}`) }); +const confirmDialog = (page: Page) => page.getByTestId("confirm-dialog"); + async function openPeople(page: Page, search = "") { await page.goto(`/admin/people?mock${search}`); await expect(row(page, "Morgan Diaz")).toBeVisible({ timeout: 20_000 }); @@ -18,24 +27,21 @@ test("a role changes inline, and promoting to admin asks first", async ({ page, }) => { await openPeople(page); - await expect(roleOf(page, "Morgan Diaz")).toHaveValue("viewer"); - await roleOf(page, "Morgan Diaz").selectOption("developer"); - await expect(roleOf(page, "Morgan Diaz")).toHaveValue("developer"); - - const asked: string[] = []; - page.once( - "dialog", - (dialog) => (asked.push(dialog.message()), void dialog.dismiss()), + await expect(roleOf(page, "Morgan Diaz")).toHaveText(/^viewer/); + await pickRole(page, roleOf(page, "Morgan Diaz"), "developer"); + await expect(roleOf(page, "Morgan Diaz")).toHaveText(/^developer/); + + await pickRole(page, roleOf(page, "Morgan Diaz"), "admin"); + await expect(confirmDialog(page)).toContainText( + "Make Morgan Diaz an admin?", ); - await roleOf(page, "Morgan Diaz").selectOption("admin"); - await expect(roleOf(page, "Morgan Diaz")).toHaveValue("developer"); - expect(asked).toEqual([ - expect.stringMatching(/^Make Morgan Diaz \(morgan\) an admin\?/), - ]); - - page.once("dialog", (dialog) => void dialog.accept()); - await roleOf(page, "Morgan Diaz").selectOption("admin"); - await expect(roleOf(page, "Morgan Diaz")).toHaveValue("admin"); + await confirmDialog(page).getByRole("button", { name: "Cancel" }).click(); + await expect(confirmDialog(page)).toHaveCount(0); + await expect(roleOf(page, "Morgan Diaz")).toHaveText(/^developer/); + + await pickRole(page, roleOf(page, "Morgan Diaz"), "admin"); + await confirmDialog(page).getByRole("button", { name: "Make admin" }).click(); + await expect(roleOf(page, "Morgan Diaz")).toHaveText(/^admin/); await expect(row(page, "Morgan Diaz").getByRole("alert")).toHaveCount(0); }); @@ -44,16 +50,20 @@ test("the last admin cannot be demoted until someone else is an admin", async ({ }) => { await openPeople(page); const demo = roleOf(page, "Demo User"); - await expect(demo).toHaveValue("admin"); + await expect(demo).toHaveText(/^admin/); await expect(row(page, "Demo User")).toContainText("last admin"); + await demo.click(); for (const role of ["viewer", "operator", "developer"]) - await expect(demo.locator(`option[value="${role}"]`)).toBeDisabled(); + await expect(roleOption(page, role)).toHaveAttribute("aria-disabled", "true"); + await page.keyboard.press("Escape"); - page.once("dialog", (dialog) => void dialog.accept()); - await roleOf(page, "Morgan Diaz").selectOption("admin"); - await expect(roleOf(page, "Morgan Diaz")).toHaveValue("admin"); + await pickRole(page, roleOf(page, "Morgan Diaz"), "admin"); + await confirmDialog(page).getByRole("button", { name: "Make admin" }).click(); + await expect(roleOf(page, "Morgan Diaz")).toHaveText(/^admin/); await expect(row(page, "Demo User")).not.toContainText("last admin"); - await expect(demo.locator('option[value="developer"]')).toBeEnabled(); + await demo.click(); + await expect(roleOption(page, "developer")).not.toHaveAttribute("aria-disabled", "true"); + await page.keyboard.press("Escape"); }); test("roles that differ by location show Mixed and link to their page", async ({ @@ -88,7 +98,7 @@ test("with password sign-in, a person is added with a first password and a role" const panel = page.getByTestId("add-person-panel"); await panel.getByLabel("Sign-in name").fill("quinn"); await panel.getByLabel("First password").fill("a long first password"); - await panel.getByLabel("Role everywhere").selectOption("developer"); + await pickRole(page, panel.getByTestId("new-person-role"), "developer"); await panel.getByRole("button", { name: "Add person" }).click(); await expect(panel).toHaveCount(0); @@ -96,7 +106,7 @@ test("with password sign-in, a person is added with a first password and a role" "aria-label", "quinn", ); - await expect(roleOf(page, "quinn")).toHaveValue("developer"); + await expect(roleOf(page, "quinn")).toHaveText(/^developer/); await expect(row(page, "quinn")).toContainText("Password"); }); @@ -122,10 +132,45 @@ test("clicking a person opens their roles and enable/disable beside the list", a await row(page, "Jordan Lee").locator("td").nth(3).click(); const panel = page.getByTestId("person-panel"); await expect(panel).toContainText("Jordan Lee"); - await expect(panel.getByRole("button", { name: "Disable" })).toBeVisible(); await expect( panel.getByRole("link", { name: /Open their page/ }), ).toHaveAttribute("href", /\/admin\/people\/jordan/); await page.keyboard.press("Escape"); await expect(panel).toHaveCount(0); }); + +test("a person is disabled from the panel's menu after a confirmation, and a role removed from its row's menu", async ({ + page, +}) => { + await openPeople(page); + await row(page, "Jordan Lee").locator("td").nth(3).click(); + const panel = page.getByTestId("person-panel"); + await panel.getByTestId("person-menu").click(); + await page.getByRole("menuitem", { name: "Disable…" }).click(); + await expect(confirmDialog(page)).toContainText("Disable Jordan Lee?"); + await page.keyboard.press("Escape"); + await expect(panel).toBeVisible(); + await panel.getByTestId("person-menu").click(); + await page.getByRole("menuitem", { name: "Disable…" }).click(); + await confirmDialog(page).getByRole("button", { name: "Disable" }).click(); + await expect(row(page, "Jordan Lee")).toContainText("Disabled"); + + await page.goto("/admin/people/alex?mock"); + await page.getByTestId("assignment-menu").first().click(); + await page.getByRole("menuitem", { name: "Remove…" }).click(); + await confirmDialog(page).getByRole("button", { name: "Remove" }).click(); + await expect(confirmDialog(page)).toHaveCount(0); +}); + +test("a role's page shows a service account holder as one, linking to its panel", async ({ + page, +}) => { + await page.goto("/admin/roles/developer?mock"); + const holder = page.getByRole("link", { name: "orders-deploy" }); + await expect(holder).toHaveAttribute( + "href", + /\/admin\/people\?tab=service-accounts&open=orders-deploy/, + { timeout: 20_000 }, + ); + await expect(page.getByText("service account").first()).toBeVisible(); +}); diff --git a/ui/e2e/plan-cant-run.spec.ts b/ui/e2e/plan-cant-run.spec.ts index b0ebbc4b5d..0329bd6af6 100644 --- a/ui/e2e/plan-cant-run.spec.ts +++ b/ui/e2e/plan-cant-run.spec.ts @@ -11,20 +11,20 @@ test('a missing provider secret lists what can’t run, disables Run, and planni await page.goto(PLAN); const pane = page.locator('.pane[data-section="cant_run"]'); await expect(pane).toBeVisible({ timeout: 30_000 }); - await expect(page.getByTestId('index-cant-run')).toHaveText('Can’t run12'); - // Will run leaves out what can't run: only stg_customers is left of the 13 planned. + await expect(page.getByTestId('index-cant-run')).toHaveText('Can’t run24'); + // Will run leaves out what can't run: only stg_customers is left of the 25 planned. await expect(page.getByTestId('index-will-run')).toHaveText('Will run1'); const problem = page.getByTestId('cant-run-problem'); await expect(problem).toContainText("Can't run: provider orders_api needs ORDERS_API_KEY"); - await expect(problem).toContainText('raw__orders and the 11 nodes that read it'); - await expect(problem).toContainText("set ORDERS_API_KEY in the location's environment (or its .env), restart the location, then plan again"); + await expect(problem).toContainText('raw__orders and the 23 nodes that read it'); + await expect(problem).toContainText('set ORDERS_API_KEY in .env, then restart the location (in sqb dev, press r), or in the environment the location (or sqb dev) was started with, then restart it; after that, plan again'); await expect(pane.locator('tbody tr').first()).toContainText('provider orders_api: ORDERS_API_KEY not set'); const row = (node: string) => pane.locator('tbody tr').filter({ has: page.getByRole('link', { name: node, exact: true }) }); await expect(row('stg_orders')).toContainText('reads raw__orders'); const run = page.getByRole('button', { name: 'Run', exact: true }); await expect(run).toBeDisabled(); - await expect(page.locator('.foot .why')).toHaveText('Run is disabled: 1 missing secret. Fix it and plan again, or leave those 12 nodes out.'); + await expect(page.locator('.foot .why')).toHaveText('Run is disabled: 1 missing secret. Fix it and plan again, or leave those 24 nodes out.'); await page.getByTestId('plan-without-blocked').click(); await expect(page.getByRole('textbox', { name: 'Command' })).toHaveValue(/--exclude raw__orders stg_orders fact_orders/); diff --git a/ui/e2e/plan-graph.spec.ts b/ui/e2e/plan-graph.spec.ts index d0c8021cff..574890563d 100644 --- a/ui/e2e/plan-graph.spec.ts +++ b/ui/e2e/plan-graph.spec.ts @@ -22,10 +22,11 @@ async function cardsInside(page: Page): Promise { for (const [description, path, expectedNodes] of [ ["a rerun of a failed run", "/plan/rerun?mock&run=run-a7c1&mode=all", 3], + // The deepest chain of the mock project, sources to a Python asset: a build plan whose graph fits whole. [ "a build plan", - `/plan?mock&cmd=${encodeURIComponent("sqb build --changed")}`, - 17, + `/plan?mock&cmd=${encodeURIComponent("sqb build --select +export_revenue_csv")}`, + 10, ], ] as const) { test(`${description}'s graph draws its nodes on a canvas that fills the box`, async ({ diff --git a/ui/e2e/run-page.spec.ts b/ui/e2e/run-page.spec.ts index bfdfd703a7..a2a3e173ec 100644 --- a/ui/e2e/run-page.spec.ts +++ b/ui/e2e/run-page.spec.ts @@ -5,9 +5,9 @@ test.use({ viewport: { width: 1600, height: 1000 } }); test('a running run’s nodes that haven’t started read as waiting', async ({ page }) => { await page.goto('/runs/run-9d21?mock'); - const panel = page.getByLabel('Nodes by outcome'); - await expect(panel.locator('.group[data-group="waiting"]')).toContainText('Waiting', { timeout: 20_000 }); - await expect(panel.locator('.group[data-group="not_run"]')).toHaveCount(0); + const summary = page.getByTestId('run-summary'); + await expect(summary).toContainText(/\d+ waiting/, { timeout: 20_000 }); + await expect(summary).not.toContainText('not run'); await expect(page.locator('.gantt .note', { hasText: 'Waiting' }).first()).toBeVisible(); await expect(page.locator('.gantt .note', { hasText: /Pending|Not run/ })).toHaveCount(0); }); diff --git a/ui/e2e/service-accounts.spec.ts b/ui/e2e/service-accounts.spec.ts new file mode 100644 index 0000000000..f066062094 --- /dev/null +++ b/ui/e2e/service-accounts.spec.ts @@ -0,0 +1,101 @@ +import { expect, test, type Page } from "@playwright/test"; + +// The Service accounts tab beside People: the resting view shows state, and actions live in menus and +// dialogs. A key is shown once, in the dialog that made it; a click on the open row closes its panel. +test.use({ viewport: { width: 1500, height: 900 } }); + +const row = (page: Page, name: string) => + page.getByTestId("service-account-row").filter({ hasText: name }); +const panel = (page: Page) => page.getByTestId("service-account-panel"); + +async function openTab(page: Page, search = "") { + await page.goto(`/admin/people?mock&tab=service-accounts${search}`); + await expect(row(page, "orders-deploy")).toBeVisible({ timeout: 20_000 }); +} + +test("a click opens a service account beside the list, and a click on its row again closes it", async ({ + page, +}) => { + await openTab(page); + await row(page, "orders-deploy").locator("td").nth(2).click(); + await expect(panel(page)).toHaveAttribute("aria-label", "orders-deploy"); + await expect(page.getByTestId("service-status")).toHaveText( + /^Rotating · old key stops in \d+m$/, + ); + await expect(panel(page).getByTestId("service-key")).toHaveCount(2); + await row(page, "orders-deploy").locator("td").nth(2).click(); + await expect(panel(page)).toHaveCount(0); +}); + +test("rotating shows the new key once in its dialog, and the old key works on for the overlap", async ({ + page, +}) => { + await openTab(page, "&open=ci-runner"); + await panel(page).getByTestId("rotate-key").click(); + const dialog = page.getByTestId("rotate-dialog"); + await dialog.getByTestId("overlap-select").click(); + await page.getByRole("menuitemradio", { name: "In 24 hours" }).click(); + await dialog.getByRole("button", { name: "Rotate key" }).click(); + + await expect(dialog.getByTestId("key-reveal")).toContainText( + "won't be shown again", + ); + await expect(dialog.locator("code")).toHaveText(/^sqbk_[A-Za-z0-9]{40}$/); + await dialog.getByRole("button", { name: "Done" }).click(); + await expect(dialog).toHaveCount(0); + await expect(panel(page).getByTestId("service-key")).toHaveCount(2); + await expect(page.getByTestId("service-status")).toHaveText( + /^Rotating · old key stops in \d+h$/, + ); +}); + +test("a key is stopped and an account disabled from menus, each after a confirmation", async ({ + page, +}) => { + await openTab(page, "&open=orders-deploy"); + await panel(page).getByTestId("key-menu").nth(1).click(); + await page.getByRole("menuitem", { name: "Stop now…" }).click(); + await page + .getByTestId("confirm-dialog") + .getByRole("button", { name: "Stop key" }) + .click(); + await expect(panel(page).getByTestId("service-key")).toHaveCount(1); + + await panel(page).getByTestId("service-menu").click(); + await page.getByRole("menuitem", { name: "Disable…" }).click(); + await page + .getByTestId("confirm-dialog") + .getByRole("button", { name: "Disable" }) + .click(); + await expect(page.getByTestId("service-status")).toHaveText(/^Disabled/); + await expect(row(page, "orders-deploy")).toContainText("Disabled"); +}); + +test("adding a service account shows its first key once", async ({ page }) => { + await openTab(page); + await page.getByTestId("add-service-account").click(); + const dialog = page.getByTestId("add-service-account-dialog"); + await dialog.getByLabel("Name").fill("nightly-export"); + await dialog.getByTestId("new-service-role").click(); + await page.getByRole("menuitemradio", { name: "operator" }).click(); + await dialog.getByRole("button", { name: "Add and create key" }).click(); + + await expect(dialog.getByTestId("key-reveal")).toBeVisible(); + await dialog.getByRole("button", { name: "Done" }).click(); + await expect(panel(page)).toHaveAttribute("aria-label", "nightly-export"); + await expect(row(page, "nightly-export")).toContainText("operator"); +}); + +test("with no service accounts the tab explains them, and without permission it says why", async ({ + page, +}) => { + await page.goto("/admin/people?mock&tab=service-accounts&serviceaccounts=none"); + await expect(page.getByTestId("service-accounts-empty")).toContainText( + "No service accounts yet", + { timeout: 20_000 }, + ); + await page.goto("/admin/people?mock&as=operator&tab=service-accounts"); + await expect( + page.getByText("You don't have access to service accounts"), + ).toBeVisible({ timeout: 20_000 }); +}); diff --git a/ui/src/lib/api/client.ts b/ui/src/lib/api/client.ts index d7041ca4a6..3c9baf2f17 100644 --- a/ui/src/lib/api/client.ts +++ b/ui/src/lib/api/client.ts @@ -27,7 +27,12 @@ import type { RunEventPage, RunListQuery, RunNodeError, + RunOutputFollow, RunOutputLine, + NodeOutputIndex, + NodeOutputPage, + NodeOutputSearch, + CheckSample, RunRowPage, RunRowQuery, RunStatement, @@ -40,7 +45,7 @@ import type { NodeStates, Snapshot, RunTabCounts, - Scope, + RepublishResult, Scope, SnapshotChange, SelectionEvaluation, SelectionRequest, @@ -127,6 +132,16 @@ export interface ApiClient extends PlatformApi { /** One statement's SQL, fetched when its row is expanded. `view.sql` */ getStatementSql(scope: Scope, runId: string, statementId: string): Promise; listRunOutput(scope: Scope, runId: string): Promise; + /** The run's output from the output store since line `after` (the newest when null), with its `ctx.log` lines; null when the server keeps no output store. `view.evidence` */ + followRunOutput?(scope: Scope, runId: string, after: number | null): Promise; + /** A node's output in the output store: how much there is and its error and warning lines, read by range. `view.evidence` */ + getNodeOutputIndex?(scope: Scope, runId: string, nodeKey: string): Promise; + getNodeOutputPage?(scope: Scope, runId: string, nodeKey: string, at: { from: number; rows: number; direction: 'forward' | 'backward'; collapse: boolean; stream?: 'all' | 'stdout' | 'stderr'; around?: number }): Promise; + searchNodeOutput?(scope: Scope, runId: string, nodeKey: string, query: string, from: number, direction: 'forward' | 'backward', signal?: AbortSignal): Promise; + /** Where the server streams a node's whole output as a file. */ + nodeOutputDownloadUrl?(scope: Scope, runId: string, nodeKey: string): string; + /** A failing check's sample rows, by the check's statement. */ + getCheckSample?(scope: Scope, runId: string, statementId: string): Promise; /** One failed node's error text, fetched when its row is expanded. `view.evidence` on the node */ getRunNodeError(scope: Scope, runId: string, nodeKey: string): Promise; /** Queued runs in claim order, with why each one waits. */ @@ -188,6 +203,9 @@ export interface ApiClient extends PlatformApi { /** Asks the location to read SQLBuild's state back from the warehouse now. `connection.test` */ requestWarehouseSync(scope: Scope): Promise; + /** Asks the location to compile and publish again, and waits for the result. `location.republish` */ + republish(scope: Scope): Promise; + /** Live "changed" signals (SSE in the server client); consumers refetch or apply their payload. */ changes: ChangeSubscription; } diff --git a/ui/src/lib/api/http-audit.test.ts b/ui/src/lib/api/http-audit.test.ts index 7a507556d8..b2d511d6d0 100644 --- a/ui/src/lib/api/http-audit.test.ts +++ b/ui/src/lib/api/http-audit.test.ts @@ -62,6 +62,7 @@ describe('toAuditEntry', () => { const work = (work: Record) => allowed('location.work_requested', { request_id: 'q-1', reason: 'plan', work }); expect(work({ kind: 'plan', command: ['build', '--select', 'orders'], selection: ['model:orders'], settings: {}, fresh: false })).toBe('Plan sqb build --select orders'); expect(work({ kind: 'sync_warehouse' })).toBe('Sync the warehouse copy'); + expect(allowed('location.work_requested', { reason: 'deploy 0.58.0', work: { kind: 'republish', requested_by: 'orders-deploy' } })).toBe('Republish requested by orders-deploy: deploy 0.58.0'); expect(allowed('error.read', { run_id: 'd36ac8b2-314c-46aa', found: true })).toBe('Run d36ac8b2'); expect(allowed('output.read', { run_id: 'd36ac8b2-314c-46aa', found: false })).toBe('Run d36ac8b2, not found'); }); diff --git a/ui/src/lib/api/http-audit.ts b/ui/src/lib/api/http-audit.ts index a5226cef09..d7d9aa1a85 100644 --- a/ui/src/lib/api/http-audit.ts +++ b/ui/src/lib/api/http-audit.ts @@ -44,6 +44,7 @@ function allowedSummary(action: string, after: Record): string const work = fieldsOf(after.work); const kind = textOf(work.kind) ?? ''; if (kind === 'plan' && Array.isArray(work.command)) return `Plan sqb ${work.command.join(' ')}`; + if (kind === 'republish') return `Republish requested by ${textOf(work.requested_by) ?? 'unknown'}: ${textOf(after.reason) ?? ''}`; return WORK[kind] ?? kind; } const run = textOf(after.run_id); @@ -59,7 +60,7 @@ export function toAuditEntry(wire: Wire['SecurityAuditEvent']): AuditEntry { return { id: wire.event_id, at: wire.occurred_at, - actor: { kind: wire.actor_name ? 'user' : 'system', name, displayName: name }, + actor: { kind: wire.actor_kind === 'service' ? 'service' : wire.actor_name ? 'user' : 'system', name, displayName: name }, action: denied ? (textOf(scope.action) ?? DENIED) : wire.action, outcome: denied ? 'denied' : 'allowed', scope: scopeOf(scope), diff --git a/ui/src/lib/api/http-client.test.ts b/ui/src/lib/api/http-client.test.ts index 06a566de19..b3125878d1 100644 --- a/ui/src/lib/api/http-client.test.ts +++ b/ui/src/lib/api/http-client.test.ts @@ -753,6 +753,26 @@ describe('administration writes', () => { }); }); +describe('republish', () => { + it('asks once with CSRF, then waits until the location published', async () => { + const states = ['pending', 'pending', 'published']; + const calls: Request[] = []; + vi.stubGlobal('document', { cookie: '__Host-sqb-csrf=token-1' }); + vi.stubGlobal( + 'fetch', + vi.fn(async (request: Request) => { + calls.push(request); + return Response.json({ state: states[calls.length - 1], generation: 7 }); + }) + ); + const client = createHttpClient({ baseUrl: 'http://ui.test', onUnauthorized: () => {} }); + expect(await client.republish(ORDERS)).toEqual({ state: 'published', generation: 7, error: null }); + expect(calls.map((c) => c.method)).toEqual(['POST', 'GET', 'GET']); + expect(calls[0].headers.get('x-sqb-csrf')).toBe('token-1'); + expect(new URL(calls[0].url).pathname).toBe('/api/control/locations/0191f0aa-orders/targets/development/republish'); + }); +}); + describe('requestWarehouseSync', () => { function server(status: number) { const calls: Request[] = []; diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index 4213eceea5..1f1ec68b7e 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -5,11 +5,13 @@ import type { components, paths } from '$control/schema.d.ts'; import { ApiError, isUnsupported, type ApiClient } from './client'; import { applyNodeStates } from './node-states'; import { checkDetailOf, toCheck, toCheckEvidence, toCheckSql } from './http-checks'; +import { LIVE_OUTPUT_ROWS, SEARCH_PARTS, followedOutput, outputLive, pageQuery, toNodeOutputIndex, toNodeOutputPage, toRunOutputLines, type NodeOutputAt } from './http-output'; import { findNode, nodeDetailOf, toCatalogNodes, nodeJobsOf, toMicrobatchCoverage, toNodeRuns, toColumnLineage, toNodeStates, toNodeStatusDelta } from './http-catalog'; import { auditMatches, toAuditEntry } from './http-audit'; import { toSnapshotChanges } from './http-changes'; import { manualConnectionTest, missingSecretsEventOf, snapshotOf, toLocationDetail, toLocationSummary, toWarehouseConnection, warehouseSyncOf } from './http-locations'; import { toAccount, toRoleAssignments, toServerSettings } from './http-people'; +import { toIssuedKey, toServiceAccount } from './http-service-accounts'; import { toMaintenanceHistory } from './http-maintenance'; import { toProviders } from './http-providers'; import { overviewOf } from './http-overview'; @@ -20,10 +22,10 @@ import { timelineOf } from './http-timeline'; import { RUN_WINDOW, groupRunNodes, parseRunCursor, planResultOf, queueEntriesOf, toAdhocCheck, runDetailOf, runRowPageOver, runsMatching, runTabCountsOf, toRunNode, toRuns, toRunEvent, toRunOutput, toRunStatements, toIgnoredAuditFailures, toRunCostRows, toCostSummary, toNodeBuildCosts } from './http-runs'; import { toSelectionEvaluation, toSelectionVocabulary } from './http-selection'; import type { ChangeSubscription, ChangedChannel, ChangedSignal, ConnectionState } from './signals'; -import type { AuthMode, Bootstrap, Capability, Location, NavCounts, PlatformEvent, Scope, Snapshot, WarehouseSync } from './types'; -import type { Account, AuditEntry, AuditQuery, ConnectionTest, LocationDetail, NewPasswordAccount, ServerSettings, WarehouseConnection, LocationSummary, PlatformEventQuery, PlatformEventRecord, PlatformHealth, MaintenanceHistory, ProviderConnection, RoleAssignment, RoleAssignmentRequest, RoleDefinition, RoleDetail } from './types/platform'; +import type { AuthMode, Bootstrap, BuiltInRole, Capability, Location, NavCounts, PlatformEvent, RepublishResult, Scope, Snapshot, WarehouseSync } from './types'; +import type { Account, AuditEntry, AuditQuery, ConnectionTest, IssuedToken, KeyRotation, LocationDetail, NewPasswordAccount, NewServiceAccount, ServiceAccount, ServerSettings, WarehouseConnection, LocationSummary, PlatformEventQuery, PlatformEventRecord, PlatformHealth, MaintenanceHistory, ProviderConnection, RoleAssignment, RoleAssignmentRequest, RoleDefinition, RoleDetail } from './types/platform'; import type { Acknowledgement, CatalogNode, CatalogNodeDetail, Check, CheckDetail, CheckEvidence, CheckSql, NodeStates, NodeStatusDelta, Overview, SnapshotChange, ColumnLineage, AttentionAcknowledgement, ConditionShape, AutomaticWithdrawal } from './types/build'; -import type { AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, RerunMode, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunNodeError, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostSummary, NodeBuildCost, StatementSql } from './types/operate'; +import type { NodeOutputIndex, NodeOutputPage, NodeOutputSearch, RunNode, RunOutputFollow, AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, RerunMode, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunNodeError, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostSummary, NodeBuildCost, StatementSql } from './types/operate'; import { newRequestId } from '$lib/browser/request-id'; type Wire = components['schemas']; @@ -84,6 +86,12 @@ const SUPPORTED: ReadonlySet = new Set([ 'disableAccount', 'enableAccount', 'createPasswordAccount', + 'listServiceAccounts', + 'createServiceAccount', + 'rotateServiceAccountKey', + 'revokeServiceAccountKey', + 'setServiceAccountDisabled', + 'setServiceAccountRole', 'listLocations', 'getLocation', 'listPlatformEvents', @@ -94,6 +102,7 @@ const SUPPORTED: ReadonlySet = new Set([ 'getLatestSnapshot', 'getWarehouseSync', 'requestWarehouseSync', + 'republish', 'maintenanceHistory', 'testConnection', 'listWarehouseConnections', @@ -111,6 +120,8 @@ const SUPPORTED: ReadonlySet = new Set([ /** How often a connection test asks for the location's answer, and the longest it waits. */ const CONNECTION_TEST_POLL_MS = 1000; +/** How long one republish poll holds open; the server ends the wait once the request expires. */ +const REPUBLISH_WAIT_SECONDS = 20; const CONNECTION_TEST_WAIT_MS = 60_000; /** How often the plan page asks for the location's plan; the server expires a plan after ten minutes. */ @@ -416,9 +427,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, }, async listRunEvents(scope: Scope, runId: string, query: { after?: number; limit?: number } = {}): Promise { const limit = query.limit ?? 1000; - const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/events', { - params: { path: runPath(scope, runId), query: { after: query.after, limit } } - }); + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/events', { params: { path: runPath(scope, runId), query: { after: query.after, limit } } }); if (response.status === 401) onUnauthorized(); if (!data) throw new ApiError(errorText(error, response), response.status); return { events: data.flatMap((e) => toRunEvent(e, runId) ?? []), nextCursor: data.length === limit ? (data.at(-1)?.storage_id ?? null) : null }; @@ -471,13 +480,80 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, async listRunOutput(scope: Scope, runId: string): Promise { const refusal = `${scope.locationId}|${runId}`; if (!evidenceLocations.has(scope.locationId) || outputRefused.has(refusal)) return []; + // The output store's newest lines, each with its node; a server that keeps no output store answers from Recall. + const [lines, index] = await Promise.all([ + http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/lines', { params: { path: runPath(scope, runId), query: { tail: true, limit: LIVE_OUTPUT_ROWS } } }), + http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/index', { params: { path: runPath(scope, runId) } }) + ]); + if (lines.response.status === 401) onUnauthorized(); + if (lines.response.status === 403) outputRefused.add(refusal); + if (lines.response.status === 403) return []; + if (lines.data && index.data) return toRunOutputLines(lines.data, index.data); const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output', { params: { path: runPath(scope, runId) } }); if (response.status === 401) onUnauthorized(); - if (response.status === 403) outputRefused.add(refusal); if (response.status === 403) return []; if (!data) throw new ApiError(errorText(error, response), response.status); return toRunOutput(data); }, + async followRunOutput(scope: Scope, runId: string, after: number | null): Promise { + const refusal = `${scope.locationId}|${runId}`; + if (!evidenceLocations.has(scope.locationId) || outputRefused.has(refusal)) return { lines: [], logs: [], last: 0, replaced: true }; + const lines = (query: { from?: number; tail?: boolean }) => + http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/lines', { params: { path: runPath(scope, runId), query: { ...query, limit: LIVE_OUTPUT_ROWS } } }); + // The index (each node's totals and its `ctx.log` lines) once, beside the lines since the last read. + const [index, page] = await Promise.all([ + http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/index', { params: { path: runPath(scope, runId) } }), + lines(after == null ? { tail: true } : { from: after + 1 }) + ]); + if (page.response.status === 401) onUnauthorized(); + if (page.response.status === 403) outputRefused.add(refusal); + if (page.response.status === 403) return { lines: [], logs: [], last: 0, replaced: true }; + // A server that keeps no output store: the caller reads Recall's output instead. + if (!page.data || !index.data) return null; + // Too many new lines to read on from the last: start again from the newest. + const fresh = after != null && page.data.next != null ? (await lines({ tail: true })).data : null; + return followedOutput(fresh ?? page.data, index.data, runId, after == null || fresh != null); + }, + async getNodeOutputIndex(scope: Scope, runId: string, nodeKey: string): Promise { + if (!evidenceLocations.has(scope.locationId)) return null; + const [{ data, error, response }, nodes] = await Promise.all([ + http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/index', { params: { path: runPath(scope, runId), query: { node: nodeKey } } }), + runNodes(scope, runId) + ]); + if (response.status === 401) onUnauthorized(); + if (response.status === 403 || response.status === 503) return null; + if (!data) throw new ApiError(errorText(error, response), response.status); + return toNodeOutputIndex(data, nodeKey, outputLive(nodes.map((n) => ({ nodeKey: n.node_key, status: n.status as RunNode['status'] })), nodeKey)); + }, + async getNodeOutputPage(scope: Scope, runId: string, nodeKey: string, at: NodeOutputAt): Promise { + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/lines', { + params: { path: runPath(scope, runId), query: pageQuery(nodeKey, at) } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toNodeOutputPage(data); + }, + async searchNodeOutput(scope: Scope, runId: string, nodeKey: string, query: string, from: number, direction: 'forward' | 'backward', signal?: AbortSignal): Promise { + // A large output is searched a bounded part at a time: carry on from where each part stopped, + // for a few parts, then hand back where to search on. A newer search aborts this one. + const searchFrom = async (start: number): Promise => { + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/runs/{run_id}/output/search', { + params: { path: runPath(scope, runId), query: { node: nodeKey, text: query, from: start, direction } }, + signal + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return data; + }; + let found: Wire['OutputSearch'] = await searchFrom(from); + for (let part = 1; part < SEARCH_PARTS && found.line == null && found.continue_from != null; part++) found = await searchFrom(found.continue_from); + return { line: found.line ?? null, count: found.count ?? null, rank: found.rank ?? null, continueFrom: found.line == null ? (found.continue_from ?? null) : null }; + }, + nodeOutputDownloadUrl(scope: Scope, runId: string, nodeKey: string): string { + const { location_id, target, run_id } = runPath(scope, runId); + const path = `/api/control/locations/${encodeURIComponent(location_id)}/targets/${encodeURIComponent(target)}/runs/${encodeURIComponent(run_id)}/output/download`; + return `${baseUrl}${path}?node=${encodeURIComponent(nodeKey)}`; + }, async getRunNodeError(scope: Scope, runId: string, nodeKey: string): Promise { const refusal = `${scope.locationId}|${runId}|${nodeKey}`; if (!evidenceLocations.has(scope.locationId) || errorRefused.has(refusal)) throw new ApiError("You may not view this node's error text", 403); @@ -684,6 +760,28 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, if (response.status === 401) onUnauthorized(); if (!response.ok) throw new ApiError(errorText(error, response), response.status); }, + /** Asks the location to publish again, then long-polls until it has or the request expires. */ + async republish(scope: Scope): Promise { + const { locationId, target } = parseLocationKey(scope.locationId); + const path = { location_id: locationId, target }; + const requestId = newRequestId(); + const asked = await http.POST('/api/control/locations/{location_id}/targets/{target}/republish', { + body: { request_id: requestId, reason: 'Requested from the web UI' }, + params: { path, query: { wait: REPUBLISH_WAIT_SECONDS }, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } + }); + if (asked.response.status === 401) onUnauthorized(); + if (!asked.data) throw new ApiError(errorText(asked.error, asked.response), asked.response.status); + let status = asked.data; + while (status.state === 'pending') { + const { data, error, response } = await http.GET('/api/control/locations/{location_id}/targets/{target}/republish/{request_id}', { + params: { path: { ...path, request_id: requestId }, query: { wait: REPUBLISH_WAIT_SECONDS } } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + status = data; + } + return { state: status.state, generation: status.generation ?? null, error: status.error ?? null }; + }, /** Asks the location to connect, then waits for its answer until the request expires. */ async testConnection(scope: Scope): Promise { const { locationId, target } = parseLocationKey(scope.locationId); @@ -796,8 +894,10 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, return role ? roleDetailOf(role, assignments, locationId) : null; }, async listRoleAssignments(): Promise { - // Group members come from the people read; without it, SSO-derived roles stay unlisted. - return toRoleAssignments(await roleHoldings(), await people().catch(() => [])); + // Group members come from the people read; without it, SSO-derived roles stay unlisted, and without + // the service account read its holders read as people. + const [holdings, members, services] = await Promise.all([roleHoldings(), people().catch(() => []), serviceAccounts().catch(() => [])]); + return toRoleAssignments(holdings, members, new Set(services.map((s) => s.name))); }, async createRoleAssignment(request: RoleAssignmentRequest): Promise { const person = await personNamed(request.principal); @@ -827,6 +927,51 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, if (!response.ok) throw new ApiError(errorText(error, response), response.status); return toAccount(await personNamed(request.name)); }, + listServiceAccounts: async (): Promise => (await serviceAccounts()).map(toServiceAccount), + async createServiceAccount(request: NewServiceAccount): Promise> { + const { data, error, response } = await http.POST('/api/admin/service-accounts', { + body: { name: request.name, description: request.description, role: request.role }, + params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toIssuedKey(data); + }, + async rotateServiceAccountKey(name: string, rotation: KeyRotation): Promise> { + const { data, error, response } = await http.POST('/api/admin/service-accounts/{principal_id}/keys', { + body: { overlap_minutes: rotation.overlapMinutes }, + params: { path: { principal_id: await serviceAccountId(name) }, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toIssuedKey(data); + }, + async revokeServiceAccountKey(name: string, keyId: string): Promise { + const { data, error, response } = await http.POST('/api/admin/service-accounts/{principal_id}/keys/{key_id}/revoke', { + params: { path: { principal_id: await serviceAccountId(name), key_id: keyId }, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toServiceAccount(data); + }, + async setServiceAccountDisabled(name: string, disabled: boolean): Promise { + const { data, error, response } = await http.POST('/api/admin/service-accounts/{principal_id}/disabled', { + body: { disabled }, + params: { path: { principal_id: await serviceAccountId(name) }, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toServiceAccount(data); + }, + async setServiceAccountRole(name: string, role: BuiltInRole): Promise { + const { data, error, response } = await http.POST('/api/admin/service-accounts/{principal_id}/role', { + body: { role }, + params: { path: { principal_id: await serviceAccountId(name) }, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } + }); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toServiceAccount(data); + }, async getColumnLineage(scope: Scope, ref: string, listing?: CatalogNode[]): Promise { const nodes = listing ?? (await listingWithStates(scope)); const node = findNode(nodes, ref); @@ -1146,6 +1291,20 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, return toAccount(await personNamed(name)); } + async function serviceAccounts() { + const { data, error, response } = await http.GET('/api/admin/service-accounts'); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return data; + } + + /** The server numbers service accounts; the UI names them, as it does people. */ + async function serviceAccountId(name: string): Promise { + const account = (await serviceAccounts()).find((a) => a.name === name); + if (!account) throw new ApiError(`No service account named ${name}`, 404); + return account.principal_id; + } + async function people() { const { data, error, response } = await http.GET('/api/admin/people'); if (response.status === 401) onUnauthorized(); @@ -1384,6 +1543,13 @@ export async function loginWithPassword(username: string, password: string, base return response.status === 401 ? 'rejected' : 'unavailable'; } +/** Whether the server takes only service account keys, so the sign-in page offers no password. */ +export async function keysOnly(baseUrl = ''): Promise { + const http = createFetch({ baseUrl, credentials: 'same-origin' }); + const { data } = await http.GET('/api/auth/login-mode'); + return data?.login_mode === 'keys'; +} + export async function logout(baseUrl = ''): Promise { const http = createFetch({ baseUrl, credentials: 'same-origin' }); await http.POST('/api/auth/logout', { params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); diff --git a/ui/src/lib/api/http-jobs.ts b/ui/src/lib/api/http-jobs.ts index ec80abddea..164b5f5b20 100644 --- a/ui/src/lib/api/http-jobs.ts +++ b/ui/src/lib/api/http-jobs.ts @@ -129,6 +129,7 @@ function toEvaluation(wire: Wire['PersonSensorEvaluation']): SensorEvaluation { error: wire.error ?? null, abandonedBecause: wire.abandoned_because ?? null, skippedBy: wire.skipped_by ?? null, + unreadable: wire.unreadable ?? null, definitionFingerprint: wire.definition_fingerprint }; } diff --git a/ui/src/lib/api/http-locations.test.ts b/ui/src/lib/api/http-locations.test.ts index 9df725200b..e1172e8c47 100644 --- a/ui/src/lib/api/http-locations.test.ts +++ b/ui/src/lib/api/http-locations.test.ts @@ -60,13 +60,24 @@ describe('location health', () => { occurredAt: at(10), members: ['ORDERS_API_KEY'], locationId: 'loc-1:prod', - message: "orders_api is missing ORDERS_API_KEY in the location's environment, so runs of the node that uses it stop before the warehouse." + message: "orders_api is missing ORDERS_API_KEY in the location's environment, so runs of raw_orders stop before the warehouse." }); + const many = { ...orders, nodes: ['source:a', 'model:b', 'model:c', 'model:d', 'asset:e'] }; + expect(missingSecretsEventOf('loc-1:prod', [seen(4, { kind: 'provider_secrets', generation: 4, missing: 1, providers: [many] })])?.message).toBe( + "orders_api is missing ORDERS_API_KEY in the location's environment, so runs of a, b, c and 2 more stop before the warehouse." + ); const allowedOnly = seen(5, { kind: 'provider_secrets', generation: 3, missing: 0, providers: [bucket] }); expect(missingSecretsEventOf('loc-1:prod', [allowedOnly, newest])).toBeNull(); expect(healthOf([allowedOnly], now).health).toBe('healthy'); }); + it('reports a failed discover function ahead of a failed connection until a newer publish discovers it', () => { + const failed = seen(10, { kind: 'discovery', generation: 2, sets: [{ name: 'orders_plan', status: 'failed', error: 'ssh timeout', items: 11 }] }); + const unhealthy = seen(10, { kind: 'connection', generation: 2, healthy: false }); + expect(healthOf([failed, unhealthy], now).health).toBe('discovery_failed'); + expect(healthOf([seen(5, { kind: 'discovery', generation: 3, sets: [{ name: 'orders_plan', status: 'ok', items: 12 }] }), failed], now).health).toBe('healthy'); + }); + it('needs attention when the latest connection check failed', () => { const observations = [seen(5, { kind: 'connection', generation: 2, healthy: false }), seen(60, { kind: 'connection', generation: 1, healthy: true })]; expect(healthOf(observations, now).health).toBe('degraded'); diff --git a/ui/src/lib/api/http-locations.ts b/ui/src/lib/api/http-locations.ts index 6c2d84bd0c..582e7a269a 100644 --- a/ui/src/lib/api/http-locations.ts +++ b/ui/src/lib/api/http-locations.ts @@ -1,3 +1,4 @@ +import { shortName } from '$lib/build-area/labels'; import type { components } from '$control/schema.d.ts'; import type { Location, LocationHealth, PlatformEvent, Snapshot, WarehouseSync } from './types'; import type { ConnectionDetails, ConnectionTest, LocationDetail, MissingProviderSecrets, PoolCapWarning, LocationInstance, LocationSummary, WarehouseConnection, WarehouseTableSync } from './types/platform'; @@ -11,7 +12,7 @@ function latestOf(observations: Wire[' return observations.find((o) => o.report.health.kind === kind) as (Wire['LocationHealthObservation'] & { report: { health: Extract } }) | undefined; } -/** Health from the newest observations: down without a recent check-in, then load failures, then missing provider secrets, then connection failures. */ +/** Health from the newest observations: down without a recent check-in, then load failures, then missing provider secrets, then failed discover functions, then connection failures. */ export function healthOf(observations: Wire['LocationHealthObservation'][], now: number): { health: LocationHealth; liveInstances: number; lastSeenAt: string | null } { // The server's own pool-cap warning is not a location check-in. const reported = observations.filter((o) => o.report.health.kind !== 'pool_capped'); @@ -20,13 +21,16 @@ export function healthOf(observations: Wire['LocationHealthObservation'][], now: const failed = latestOf(observations, 'compile_failed'); const connection = latestOf(observations, 'connection'); const secrets = latestOf(observations, 'provider_secrets'); + const discovery = latestOf(observations, 'discovery'); const health: LocationHealth = !live.size ? 'broken' : failed && (!connection || failed.report.health.generation >= connection.report.health.generation) ? 'falling_back' : secrets && secrets.report.health.missing > 0 ? 'missing_secrets' - : connection && !connection.report.health.healthy + : discovery && discovery.report.health.sets.some((set) => set.status === 'failed') + ? 'discovery_failed' + : connection && !connection.report.health.healthy ? 'degraded' : 'healthy'; return { health, liveInstances: live.size, lastSeenAt }; @@ -39,6 +43,12 @@ export function missingSecretsOf(observations: Wire['LocationHealthObservation'] return [...providers.filter((p) => !p.allowed), ...providers.filter((p) => p.allowed)]; } +/** How many nodes the missing-secrets problem names before "and N more". */ +const SECRET_NODES_SHOWN = 3; + +/** "a", "a and b", "a, b and c". */ +const andList = (parts: string[]) => (parts.length < 2 ? parts.join('') : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}`); + /** * The Overview's problem for a location whose providers miss secrets its target doesn't allow, or null. * Its members are the unset variables, so a newly missing one makes it worse. @@ -48,7 +58,13 @@ export function missingSecretsEventOf(locationKey: string, observations: Wire['L const problems = missingSecretsOf(observations).filter((p) => !p.allowed); if (!latest || !problems.length) return null; const variables = problems.flatMap((p) => p.settings.map((s) => s.variable)); - const nodes = new Set(problems.flatMap((p) => p.nodes)).size; + const nodes = [...new Set(problems.flatMap((p) => p.nodes))].map(shortName); + const it = problems.length === 1 ? 'it' : 'them'; + const stopped = !nodes.length + ? `runs that use ${it}` + : nodes.length <= SECRET_NODES_SHOWN + ? `runs of ${andList(nodes)}` + : `runs of ${nodes.slice(0, SECRET_NODES_SHOWN).join(', ')} and ${nodes.length - SECRET_NODES_SHOWN} more`; const providers = problems.map((p) => p.provider).join(', '); return { id: `secrets:${locationKey}`, @@ -59,7 +75,7 @@ export function missingSecretsEventOf(locationKey: string, observations: Wire['L active: true, locationId: locationKey, subject: null, - message: `${providers} ${problems.length === 1 ? 'is' : 'are'} missing ${variables.join(', ')} in the location's environment, so runs of ${nodes === 1 ? 'the node that uses' : `the ${nodes} nodes that use`} ${problems.length === 1 ? 'it' : 'them'} stop before the warehouse.` + message: `${providers} ${problems.length === 1 ? 'is' : 'are'} missing ${variables.join(', ')} in the location's environment, so ${stopped} stop before the warehouse.` }; } diff --git a/ui/src/lib/api/http-output.test.ts b/ui/src/lib/api/http-output.test.ts new file mode 100644 index 0000000000..0a3f84a036 --- /dev/null +++ b/ui/src/lib/api/http-output.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from 'vitest'; +import type { components } from '$control/schema.d.ts'; +import { followedOutput, outputLive, pageQuery, toNodeLogEvents, toNodeOutputIndex, toNodeOutputPage, toRunOutputLines } from './http-output'; + +type W = components['schemas']; + +const line = (number: number, text: string, extra: Partial = {}): W['OutputLine'] => ({ number, node_key: 'model:orders', stream: 'stdout', text, level: null, at: '2026-11-21T09:00:00Z', ...extra }); + +describe('node output mapping', () => { + it('reads forwards from a line and backwards from just before one, leaving out the whole-output stream', () => { + expect(pageQuery('model:orders', { from: 40, rows: 200, direction: 'forward', collapse: true, stream: 'all' })).toEqual({ node: 'model:orders', from: 40, limit: 200, collapse: true }); + expect(pageQuery('model:orders', { from: 40, rows: 200, direction: 'backward', collapse: false, stream: 'stderr', around: 38 })).toEqual({ + node: 'model:orders', + stream: 'stderr', + before: 40, + limit: 200, + collapse: false, + around: 38 + }); + }); + + it('keeps line numbers and folded runs, and reads warning as warn', () => { + const page = toNodeOutputPage({ + rows: [ + { kind: 'similar', from: 1, count: 40, sample: line(1, 'batch 1 rows=3') }, + { kind: 'line', line: line(41, 'WARNING: slow batch', { stream: 'stderr', level: 'warning' }) }, + { kind: 'line', line: line(42, 'Traceback (most recent call last):', { stream: 'stderr', level: 'error' }) } + ], + line_count: 90, + from: 1, + to: 43, + next: 43, + previous: null + }); + expect(page).toEqual({ + total: 90, + from: 1, + to: 43, + rows: [ + { kind: 'similar', from: 1, count: 40, sample: { n: 1, stream: 'stdout', text: 'batch 1 rows=3', level: 'info' } }, + { kind: 'line', line: { n: 41, stream: 'stderr', text: 'WARNING: slow batch', level: 'warn' } }, + { kind: 'line', line: { n: 42, stream: 'stderr', text: 'Traceback (most recent call last):', level: 'error' } } + ] + }); + }); + + it("takes the node's counts and marks from the index, and none for a node that printed nothing", () => { + const index: W['RunOutputIndex'] = { + nodes: [{ node_key: 'model:orders', line_count: 12, stdout_lines: 10, stderr_lines: 2, text_bytes: 480 }], + line_count: 13, + omitted_bytes: 0, + omitted_lines: 0, + dropped_bytes: 0, + logs: [], + marks: [{ line: 11, stream: 'stderr', level: 'warning', text: 'WARNING: slow batch' }] + }; + expect(toNodeOutputIndex(index, 'model:orders', true)).toEqual({ total: 12, stdout: 10, stderr: 2, bytes: 480, marks: [{ line: 11, level: 'warn', text: 'WARNING: slow batch' }], live: true }); + expect(toNodeOutputIndex(index, 'model:customers', false)).toBeNull(); + }); + + it('counts output as live while its node runs, and lines outside any node while any node does', () => { + const nodes = [ + { nodeKey: 'model:orders', status: 'running' as const }, + { nodeKey: 'model:customers', status: 'success' as const } + ]; + expect([outputLive(nodes, 'model:orders'), outputLive(nodes, 'model:customers'), outputLive(nodes, 'run'), outputLive(nodes.slice(1), 'run')]).toEqual([true, false, true, false]); + }); + + it('turns the lines nodes logged with ctx.log into the run’s events, at their level', () => { + const index: W['RunOutputIndex'] = { + nodes: [], + line_count: 0, + omitted_bytes: 0, + omitted_lines: 0, + dropped_bytes: 0, + marks: [], + logs: [ + { node_key: 'asset:score_customers', level: 'info', message: 'scored 120 customers', logged_at: '2026-11-21T09:00:00Z' }, + { node_key: 'asset:score_customers', level: 'warning', message: '3 customers had no orders', logged_at: '2026-11-21T09:00:01Z' } + ] + }; + expect(toNodeLogEvents(index, 'run-1').map((e) => [e.type, e.nodeKey, e.level, e.message, e.occurredAt])).toEqual([ + ['node_log', 'asset:score_customers', 'info', 'scored 120 customers', '2026-11-21T09:00:00Z'], + ['node_log', 'asset:score_customers', 'warn', '3 customers had no orders', '2026-11-21T09:00:01Z'] + ]); + }); + + it('tags the run’s newest lines with their node, and counts a node’s earlier lines before its first one shown', () => { + const page: W['OutputPage'] = { + rows: [ + { kind: 'line', line: line(41, 'Run inputs verified.', { node_key: 'run', stream: 'stderr' }) }, + { kind: 'line', line: line(42, 'batch 40 done') }, + { kind: 'line', line: line(43, 'loaded customers', { node_key: 'model:customers' }) } + ], + line_count: 43, + from: 41, + to: 44, + next: null, + previous: 41 + }; + const index: W['RunOutputIndex'] = { + nodes: [ + { node_key: 'model:customers', line_count: 1, stdout_lines: 1, stderr_lines: 0, text_bytes: 17 }, + { node_key: 'model:orders', line_count: 40, stdout_lines: 40, stderr_lines: 0, text_bytes: 600 }, + { node_key: 'run', line_count: 2, stdout_lines: 1, stderr_lines: 1, text_bytes: 40 } + ], + line_count: 43, + omitted_bytes: 0, + omitted_lines: 0, + dropped_bytes: 0, + marks: [], + logs: [] + }; + expect(toRunOutputLines(page, index).map((l) => [l.nodeKey, l.stream, l.text, l.omitted ?? 0])).toEqual([ + [null, 'stderr', 'Run inputs verified.', 0], + ['model:orders', 'stdout', '', 39], + ['model:orders', 'stdout', 'batch 40 done', 0], + ['model:customers', 'stdout', 'loaded customers', 0] + ]); + }); + + it('reads a follow as the newest lines with markers, or as new lines alone, and carries on from the last line', () => { + const index: W['RunOutputIndex'] = { + nodes: [{ node_key: 'model:orders', line_count: 50, stdout_lines: 50, stderr_lines: 0, text_bytes: 600 }], + line_count: 50, + omitted_bytes: 0, + omitted_lines: 0, + dropped_bytes: 0, + marks: [], + logs: [{ node_key: 'model:orders', level: 'info', message: 'halfway', logged_at: '2026-11-21T09:00:00Z' }] + }; + const page: W['OutputPage'] = { rows: [{ kind: 'line', line: line(50, 'done') }], line_count: 50, from: 50, to: 51, next: null, previous: 50 }; + const newest = followedOutput(page, index, 'r1', true); + const since = followedOutput(page, index, 'r1', false); + expect([newest.lines.map((l) => l.omitted ?? 0), since.lines.map((l) => l.omitted ?? 0), newest.last, newest.logs.length, since.replaced]).toEqual([[49, 0], [0], 50, 1, false]); + }); +}); diff --git a/ui/src/lib/api/http-output.ts b/ui/src/lib/api/http-output.ts new file mode 100644 index 0000000000..51a7fad33c --- /dev/null +++ b/ui/src/lib/api/http-output.ts @@ -0,0 +1,105 @@ +import type { components } from '$control/schema.d.ts'; +import type { NodeOutputIndex, NodeOutputLevel, NodeOutputLine, NodeOutputPage, NodeOutputRow, RunEvent, RunNode, RunOutputFollow, RunOutputLine } from './types/operate'; + +type Wire = components['schemas']; + +/** Where a page of a node's output starts, which way it reads, and how. */ +export type NodeOutputAt = { from: number; rows: number; direction: 'forward' | 'backward'; collapse: boolean; stream?: 'all' | 'stdout' | 'stderr'; around?: number }; + +/** The query of a page of a node's output: forwards from `from`, or backwards from just before it. */ +export function pageQuery(nodeKey: string, at: NodeOutputAt) { + return { + node: nodeKey, + ...(at.stream && at.stream !== 'all' ? { stream: at.stream } : {}), + ...(at.direction === 'forward' ? { from: Math.max(1, at.from) } : { before: Math.max(1, at.from) }), + limit: at.rows, + collapse: at.collapse, + ...(at.around == null ? {} : { around: at.around }) + }; +} + +function levelOf(level: Wire['OutputLevel'] | null | undefined): NodeOutputLevel { + return level === 'error' ? 'error' : level === 'warning' ? 'warn' : 'info'; +} + +export function toNodeOutputLine(wire: Wire['OutputLine']): NodeOutputLine { + return { n: wire.number, stream: wire.stream, text: wire.text, level: levelOf(wire.level) }; +} + +function toRow(wire: Wire['OutputRow']): NodeOutputRow { + return wire.kind === 'line' ? { kind: 'line', line: toNodeOutputLine(wire.line) } : { kind: 'similar', from: wire.from, count: wire.count, sample: toNodeOutputLine(wire.sample) }; +} + +export function toNodeOutputPage(wire: Wire['OutputPage']): NodeOutputPage { + return { total: wire.line_count, from: wire.from, to: wire.to, rows: wire.rows.map(toRow) }; +} + +/** A node's index entry and marks; `live` while the node, or for lines outside any node the run, is still running. */ +export function toNodeOutputIndex(wire: Wire['RunOutputIndex'], nodeKey: string, live: boolean): NodeOutputIndex | null { + const node = wire.nodes.find((n) => n.node_key === nodeKey); + if (!node) return null; + return { + total: node.line_count, + stdout: node.stdout_lines, + stderr: node.stderr_lines, + bytes: node.text_bytes, + marks: wire.marks.map((m) => ({ line: m.line, level: m.level === 'error' ? 'error' : 'warn', text: m.text })), + live + }; +} + +/** Whether a node's output may still grow: the node is running, or, for lines outside any node, any node still is. */ +export function outputLive(nodes: readonly Pick[], nodeKey: string): boolean { + const running = (n: Pick) => n.status === 'running' || n.status === 'pending'; + return nodeKey === 'run' ? nodes.some(running) : nodes.some((n) => n.nodeKey === nodeKey && running(n)); +} + +/** The lines a run's nodes logged with `ctx.log`, as events of the run; they come with its output, which needs `view.evidence`. */ +export function toNodeLogEvents(wire: Wire['RunOutputIndex'], runId: string): RunEvent[] { + return wire.logs.map((log, i) => ({ + id: `${runId}-log-${i + 1}`, + storageId: 0, + runId, + producer: 'sqb', + type: 'node_log', + occurredAt: log.logged_at, + level: log.level === 'error' ? 'error' : log.level === 'warning' ? 'warn' : 'info', + invocationId: null, + nodeKey: log.node_key, + statementId: null, + attempt: null, + message: log.message + })); +} + +/** Parts of a large output one search reads before it hands back where to search on. */ +export const SEARCH_PARTS = 8; + +/** The run's newest printed lines the log shows; earlier ones are in each node's output viewer. */ +export const LIVE_OUTPUT_ROWS = 2000; + +/** + * The run's newest printed lines, each with its node (none for lines printed outside any node), and, + * before a node's first line shown, how many of its earlier lines are only in its viewer. + */ +export function toRunOutputLines(page: Wire['OutputPage'], index: Wire['RunOutputIndex']): RunOutputLine[] { + const lines: Wire['OutputLine'][] = page.rows.flatMap((row) => (row.kind === 'line' ? [row.line] : [])); + const shown = new Map(); + for (const line of lines) shown.set(line.node_key, (shown.get(line.node_key) ?? 0) + 1); + const totals = new Map(index.nodes.map((n) => [n.node_key, n.line_count])); + const marked = new Set(); + return lines.flatMap((line): RunOutputLine[] => { + const nodeKey = line.node_key === 'run' ? null : line.node_key; + const printed: RunOutputLine = { invocationId: '', stream: line.stream, at: line.at, text: line.text, error: false, nodeKey }; + const earlier = (totals.get(line.node_key) ?? 0) - (shown.get(line.node_key) ?? 0); + if (!nodeKey || earlier <= 0 || marked.has(line.node_key)) return [printed]; + marked.add(line.node_key); + return [{ ...printed, text: '', omitted: earlier }, printed]; + }); +} + +/** What one follow read gives: the lines (the newest, or those since the last read), the run's `ctx.log` lines, and its last line. */ +export function followedOutput(page: Wire['OutputPage'], index: Wire['RunOutputIndex'], runId: string, replaced: boolean): RunOutputFollow { + const lines = replaced ? toRunOutputLines(page, index) : toRunOutputLines(page, { ...index, nodes: [] }); + return { lines, logs: toNodeLogEvents(index, runId), last: Math.max(page.to - 1, 0), replaced }; +} diff --git a/ui/src/lib/api/http-people.test.ts b/ui/src/lib/api/http-people.test.ts index a01a4a291d..0c051bac44 100644 --- a/ui/src/lib/api/http-people.test.ts +++ b/ui/src/lib/api/http-people.test.ts @@ -28,6 +28,24 @@ describe('people', () => { ]); }); + it('marks the service accounts among role holders, so their pages link to their panel', () => { + const assignments = toRoleAssignments( + { + assignments: [ + { assignment_id: 'a-1', principal_id: 'p-sam', name: 'sam', role_key: 'viewer', location_id: null, target: null }, + { assignment_id: 'a-2', principal_id: 'p-deploy', name: 'orders-deploy', role_key: 'developer', location_id: null, target: null } + ], + group_roles: [] + }, + [person('sam', [], true)], + new Set(['orders-deploy']) + ); + expect(assignments.map((a) => [a.principal.name, a.principal.kind])).toEqual([ + ['sam', 'user'], + ['orders-deploy', 'service'] + ]); + }); + it('reports a sign-in source only when the server knows one', () => { expect([toAccount(person('sam', [], true)).source, toAccount(person('ada', ['g'])).source, toAccount(person('vic', [])).source]).toEqual([ 'password', diff --git a/ui/src/lib/api/http-people.ts b/ui/src/lib/api/http-people.ts index 4d4f0c4a56..1b9b93360f 100644 --- a/ui/src/lib/api/http-people.ts +++ b/ui/src/lib/api/http-people.ts @@ -24,8 +24,9 @@ function scopeKey(locationId: string | null | undefined, target: string | null | } /** Assignments given here, then one SSO assignment per member of each mapped group. */ -export function toRoleAssignments(holdings: Wire['RoleHoldings'], people: Wire['PersonSummary'][]): RoleAssignment[] { - const person = (name: string) => ({ kind: 'user' as const, name, displayName: name }); +/** Role holders; `services` names the service accounts among them, which hold roles as people do. */ +export function toRoleAssignments(holdings: Wire['RoleHoldings'], people: Wire['PersonSummary'][], services: ReadonlySet = new Set()): RoleAssignment[] { + const person = (name: string) => ({ kind: services.has(name) ? ('service' as const) : ('user' as const), name, displayName: name }); const manual: RoleAssignment[] = holdings.assignments.map((a) => ({ id: a.assignment_id, principal: person(a.name), diff --git a/ui/src/lib/api/http-run-cant-run.test.ts b/ui/src/lib/api/http-run-cant-run.test.ts new file mode 100644 index 0000000000..010e111a3e --- /dev/null +++ b/ui/src/lib/api/http-run-cant-run.test.ts @@ -0,0 +1,178 @@ +// The Couldn't run blocks from the server's own wire shapes, through the HTTP client: a mock client once hid that they never showed. +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { components } from '$control/schema.d.ts'; +import { fixText, runDetailCantRun } from '$lib/run/cant-run'; +import { createHttpClient } from './http-client'; + +type Wire = components['schemas']; + +const LOCATION = '0191f0aa-orders'; +const SCOPE = { locationId: `${LOCATION}:production` }; +const RUN = '0191f0aa-0000-7000-8000-000000000001'; +const AT = '2026-11-22T06:00:00Z'; + +/** A run as the server lists it, every field present. */ +function runRecord(reason: string | null, change: Partial = {}): Wire['RunRecord'] { + return { + run_id: RUN, + location_id: LOCATION, + target: 'production', + snapshot_id: '0191f0aa-0000-7000-8000-0000000000aa', + snapshot_generation: 4, + git_revision: null, + git_dirty: false, + sqb_version: '0.259.0', + image_id: null, + job_key: 'nightly_job', + kind: 'job', + origin: 'schedule', + parent_run_id: null, + root_run_id: RUN, + trigger_id: null, + trigger_name: null, + tick_id: null, + rerun_of_run_id: null, + requested_by: 'system:scheduler', + requester_name: null, + priority: 0, + rewrite_history: false, + status: 'failed', + status_reason: reason, + queued_at: AT, + launched_at: AT, + started_at: AT, + ended_at: AT, + cancel_requested_at: null, + selection_json: [], + node_counts_json: { failed: 1 }, + ignored_audit_failures: 0, + last_event_storage_id: 9, + narrowing: null, + ...change + }; +} + +/** A node as the server lists it, every field present. */ +function nodeRecord(key: string, change: Partial): Wire['RunNodeRecord'] { + return { + node_key: key, + status: 'failed', + started_at: null, + ended_at: AT, + rows_affected: null, + table_rows: null, + rows_so_far: null, + no_change_reason: null, + materialization: null, + error_code: null, + missing_secret: null, + skipped_because_of: null, + ...change + }; +} + +const failed = (key: string, message: string | null) => nodeRecord(key, { error_code: 'D012', missing_secret: message }); +const skipped = (key: string, cause: string) => nodeRecord(key, { status: 'skipped', skipped_because_of: cause }); +const notRun = (key: string) => nodeRecord(key, { status: 'not_run' }); + +/** The run page's blocks for a server with these runs and nodes, and every path the client asked for. */ +async function blocks(runs: Wire['RunRecord'][], nodes: Record) { + const paths: string[] = []; + vi.stubGlobal('document', { cookie: '' }); + vi.stubGlobal( + 'fetch', + vi.fn(async (request: Request) => { + const path = decodeURIComponent(new URL(request.url).pathname); + paths.push(path); + if (path.endsWith('/runs')) return Response.json(runs); + const run = /\/runs\/([^/]+)\/nodes$/.exec(path)?.[1]; + return run ? Response.json(nodes[run] ?? []) : Response.json({ error: 'unexpected read' }, { status: 500 }); + }) + ); + const detail = await createHttpClient({ baseUrl: 'http://ui.test', onUnauthorized: () => {} }).getRunDetail(SCOPE, RUN); + if (!detail) throw new Error('the run was not found'); + return { entries: runDetailCantRun(detail), paths }; +} + +afterEach(() => vi.unstubAllGlobals()); + +describe("a run's Couldn't run blocks over HTTP", () => { + it('names the provider, variables, configured env file, users and readers', async () => { + const places = "the location's environment and from config/production.env"; + const { entries } = await blocks([runRecord(`Couldn't run: provider region needs REGION_CODE, REGION_TOKEN (missing from ${places}); nothing ran`)], { + [RUN]: [failed('source:raw_regions', `provider region: REGION_CODE, REGION_TOKEN not set (missing from ${places})`), skipped('model:orders', 'source:raw_regions'), notRun('model:unrelated')] + }); + expect(entries).toEqual([ + { reason: 'missing_secret', provider: 'region', path: '', variables: ['REGION_CODE', 'REGION_TOKEN'], nodes: ['source:raw_regions'], readers: ['model:orders'], sinks: [], env_file: 'config/production.env' } + ]); + expect(fixText(entries[0], 'the next run works')).toBe( + 'set REGION_CODE and REGION_TOKEN in config/production.env, then restart the location (in sqb dev, press r), or in the environment the location (or sqb dev) was started with, then restart it; after that, the next run works' + ); + }); + + it('names only the environment when the location loads no env file', async () => { + const places = "the location's environment"; + const { entries } = await blocks([runRecord(`Couldn't run: provider region needs REGION_CODE (missing from ${places}); nothing ran`)], { + [RUN]: [failed('source:raw_regions', `provider region: REGION_CODE not set (missing from ${places})`)] + }); + expect(entries[0].env_file).toBeNull(); + expect(fixText(entries[0], 'the next run works')).toBe('set REGION_CODE in the environment the location (or sqb dev) was started with, then restart it; after that, the next run works'); + }); + + it('gives each node its own provider, with the variables redaction took from its message', async () => { + const places = "the location's environment and from .env"; + const { entries } = await blocks([runRecord(`Couldn't run: provider orders_api_key needs ORDERS_API_KEY, ORDERS_REGION; provider region needs REGION_CODE (missing from ${places}); nothing ran`)], { + [RUN]: [failed('source:raw_orders', `provider orders_api_key: [REDACTED], ORDERS_REGION not set (missing from ${places})`), failed('source:raw_regions', `provider region: REGION_CODE not set (missing from ${places})`)] + }); + expect(entries.map((e) => [e.provider, e.variables, e.nodes])).toEqual([ + ['orders_api_key', ['ORDERS_API_KEY', 'ORDERS_REGION'], ['source:raw_orders']], + ['region', ['REGION_CODE'], ['source:raw_regions']] + ]); + }); + + it('reads a thousand nodes failed on one secret with the one node listing', async () => { + const places = "the location's environment and from .env"; + const keys = Array.from({ length: 1000 }, (_, i) => `loader:orders_${i}`); + const { entries, paths } = await blocks([runRecord(`Couldn't run: provider region needs REGION_CODE (missing from ${places}); nothing ran`)], { + [RUN]: keys.map((key) => failed(key, `provider region: REGION_CODE not set (missing from ${places})`)) + }); + expect(entries.map((e) => e.nodes)).toEqual([keys]); + expect(paths.map((path) => path.split('/targets/production')[1])).toEqual(['/runs', `/runs/${RUN}/nodes`]); + }); + + it('shows a sink, which fails no node, alone or beside its provider', async () => { + const places = "the location's environment and from .env"; + const alone = await blocks([runRecord(`Couldn't run: sink run_log needs LOG_TOKEN; every run uses sinks (missing from ${places}); nothing ran`)], { [RUN]: [notRun('model:orders')] }); + expect(alone.entries).toMatchObject([{ provider: '', variables: ['LOG_TOKEN'], nodes: [], sinks: ['run_log'], env_file: '.env' }]); + vi.unstubAllGlobals(); + const beside = await blocks([runRecord(`Couldn't run: provider chat needs CHAT_URL; sink run_log needs CHAT_URL; every run uses sinks (missing from ${places}); nothing ran`)], { + [RUN]: [failed('asset:notify', `provider chat: CHAT_URL not set (missing from ${places})`)] + }); + expect(beside.entries).toMatchObject([{ provider: 'chat', variables: ['CHAT_URL'], nodes: ['asset:notify'], sinks: ['run_log'] }]); + }); + + it("reads a group's blocks from its job runs", async () => { + const child = '0191f0aa-0000-7000-8000-000000000002'; + const places = "the location's environment and from .env"; + const group = runRecord('a job failed', { kind: 'group', job_key: 'nightly_job_group' }); + const member = runRecord(`Couldn't run: provider region needs REGION_CODE (missing from ${places}); nothing ran`, { run_id: child, parent_run_id: RUN }); + const { entries } = await blocks([group, member], { + [RUN]: [failed('source:raw_regions', null)], + [child]: [failed('source:raw_regions', `provider region: REGION_CODE not set (missing from ${places})`)] + }); + expect(entries).toMatchObject([{ provider: 'region', nodes: ['source:raw_regions'] }]); + }); + + it('still names the provider once history is pruned and after a note on the reason', async () => { + const reason = "Couldn't run: provider region needs REGION_CODE (missing from the location's environment); nothing ran; not retried: this run's snapshot can't be read"; + const { entries } = await blocks([runRecord(reason)], { [RUN]: [failed('source:raw_regions', null)] }); + expect(entries).toMatchObject([{ provider: 'region', variables: ['REGION_CODE'], nodes: ['source:raw_regions'], env_file: null }]); + }); + + it('shows nothing for other failures', async () => { + const { entries } = await blocks([runRecord('worker executor completed and closed its connections')], { + [RUN]: [nodeRecord('asset:notify', { error_code: 'D012', started_at: AT })] + }); + expect(entries).toEqual([]); + }); +}); diff --git a/ui/src/lib/api/http-runs.test.ts b/ui/src/lib/api/http-runs.test.ts index 7a67c1d023..f43e4140ab 100644 --- a/ui/src/lib/api/http-runs.test.ts +++ b/ui/src/lib/api/http-runs.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import type { components } from '$control/schema.d.ts'; -import { groupRunNodes, mergePlanPage, parseRunCursor, queueEntriesOf, planResultOf, runDetailOf, runRowPage, runRowPageOver, runTabCountsOf, toRunNode, toRuns, toRunEvent, toRunStatements, toRunOutput } from './http-runs'; +import { groupRunNodes, mergePlanPage, nodeKindOf, parseRunCursor, queueEntriesOf, planResultOf, runDetailOf, runRowPage, runRowPageOver, runTabCountsOf, toRunNode, toRuns, toRunEvent, toRunStatements, toRunOutput } from './http-runs'; type RunRecord = components['schemas']['RunRecord']; type W = components['schemas']; @@ -51,17 +51,17 @@ describe('run mapping', () => { expect([part.narrowing, whole.narrowing]).toEqual([{ select: [], exclude: ['customers'] }, null]); }); - it('counts cancelled nodes as failed and counts each run’s direct children', () => { + it('counts cancelled nodes as failed, not-run nodes among the skipped as well as on their own, and each run’s direct children', () => { const runs = toRuns( [ - wire('group', { kind: 'group', node_counts_json: { success: 3, cancelled: 2, failed: 1, pending: 4 } }), + wire('group', { kind: 'group', node_counts_json: { success: 3, cancelled: 2, failed: 1, pending: 4, skipped: 1, not_run: 2 } }), wire('child-1', { parent_run_id: 'group', root_run_id: 'group' }), wire('child-2', { parent_run_id: 'group', root_run_id: 'group' }), wire('grandchild', { parent_run_id: 'child-1', root_run_id: 'group' }) ], LOCATION ); - expect(runs[0].nodeCounts).toEqual({ success: 3, warn: 0, failed: 3, skipped: 0, running: 0, pending: 4 }); + expect(runs[0].nodeCounts).toEqual({ success: 3, warn: 0, failed: 3, skipped: 3, notRun: 2, running: 0, pending: 4 }); expect(runs.map((r) => r.childRunCount)).toEqual([2, 1, 0, 0]); }); }); @@ -94,7 +94,7 @@ describe('runs list', () => { expect(rows.find((r) => r.run.id === 'r1')?.cancelRequestedAt).toBe('2026-11-06T10:05:00Z'); expect(rows.find((r) => r.run.id === 'r2')?.cancelRequestedAt).toBeNull(); expect(rows.find((r) => r.run.id === 'r4')?.rerunFromFailureCount).toBe(5); - expect(rows.find((r) => r.run.id === 'r7')?.rerunFromFailureCount).toBe(2); + expect(rows.find((r) => r.run.id === 'r7')?.rerunFromFailureCount).toBe(4); }); it('counts active and queued runs under the filter, ignoring the tab', () => { @@ -197,7 +197,7 @@ describe('runs past the newest window', () => { }); describe('run detail', () => { - it('links parent, children and reruns, and reruns from failed and skipped nodes but not cancelled ones', () => { + it('links parent, children and reruns, and reruns from failed, cancelled, skipped and unreached nodes', () => { const wires = [ wire('parent', { kind: 'group' }), wire('run', { parent_run_id: 'parent', root_run_id: 'parent', status: 'failed' }), @@ -207,14 +207,14 @@ describe('run detail', () => { ]; const runs = toRuns(wires, LOCATION); const run = runs[1]; - const nodes = (['success', 'failed', 'skipped', 'cancelled', 'bogus'] as const).map((status, i) => + const nodes = (['success', 'failed', 'skipped', 'cancelled', 'bogus', 'not_run'] as const).map((status, i) => toRunNode({ node_key: `model.n${i}`, status, skipped_because_of: status === 'skipped' ? 'model.n1' : null } as components['schemas']['RunNodeRecord'], run) ); const detail = runDetailOf(run, wires[1], runs, nodes); expect(detail.parent?.id).toBe('parent'); expect(detail.children.map((r) => r.id)).toEqual(['child-early', 'child-late']); expect(detail.reruns.map((r) => r.id)).toEqual(['retry']); - expect(detail.rerunFromFailureNodes).toEqual(['model.n1', 'model.n2']); + expect(detail.rerunFromFailureNodes).toEqual(['model.n1', 'model.n2', 'model.n3', 'model.n4', 'model.n5']); expect(nodes[4].status).toBe('not_run'); expect(nodes[2].skippedBecauseOf).toEqual({ nodeKey: 'model.n1', runId: 'run', jobKey: 'orders_daily' }); }); @@ -266,6 +266,23 @@ describe('run Recall reads', () => { expect(toRunEvent(event('resource_attempt_started', { resource_id: '3b7370f99e385665996e8f73523b4fd5' }), 'r1')?.nodeKey).toBeNull(); }); + it('names a check result, its outcome and the rows it found; other events carry no check', () => { + const check = (outcome: string, extra: Partial = {}) => toRunEvent(event('audit_completed', { outcome, ...extra }), 'r1')?.check; + expect([ + check('warn', { check_name: 'unique(order_id)', check_rows: 14, check_binding_key: 'b-1', check_result_id: 'r-1' }), + check('error', { check_name: 'not_null(id)', check_rows: 2 }), + check('pass', { check_name: 'row_count' }), + check('insufficient', { check_name: 'freshness' }), + toRunEvent(event('resource_attempt_started'), 'r1')?.check + ]).toEqual([ + { name: 'unique(order_id)', outcome: 'warned', rows: 14, bindingKey: 'b-1', resultId: 'r-1' }, + { name: 'not_null(id)', outcome: 'failed', rows: 2, bindingKey: null, resultId: null }, + { name: 'row_count', outcome: 'passed', rows: null, bindingKey: null, resultId: null }, + { name: 'freshness', outcome: 'skipped', rows: null, bindingKey: null, resultId: null }, + null + ]); + }); + it('orders statements as sent and tells running from finished by the end time', () => { const statement = (id: string, extra: Partial): W['RunStatementRecord'] => ({ invocation_id: inv, statement_id: id, sql_available: true, ...extra }); const statements = toRunStatements( @@ -412,3 +429,16 @@ describe('mergePlanPage', () => { expect({ warnings: once.warnings, starts: once.synced_copy?.cursor_window_starts }).toEqual({ warnings: [warning], starts: { orders: '2026-11-01' } }); }); }); + +describe('run node kinds', () => { + it('read a model’s kind from its materialization and any other node’s from its key', () => { + expect([nodeKindOf('model:orders', 'incremental'), nodeKindOf('model:orders', 'view'), nodeKindOf('model:orders', null), nodeKindOf('seed:countries', null), nodeKindOf('loader:raw_events', null), nodeKindOf('check:orders_valid', null)]).toEqual([ + 'incremental', + 'view', + null, + 'seed', + 'loader', + null + ]); + }); +}); diff --git a/ui/src/lib/api/http-runs.ts b/ui/src/lib/api/http-runs.ts index 186fd3c096..f49a9fa00a 100644 --- a/ui/src/lib/api/http-runs.ts +++ b/ui/src/lib/api/http-runs.ts @@ -1,7 +1,7 @@ import type { components } from '$control/schema.d.ts'; -import { isActiveRun } from '$lib/status'; +import { isActiveRun, isUnfinishedNode, UNFINISHED_NODE_STATUSES } from '$lib/status'; import type { Capability, Principal } from './types'; -import type { AdhocRunCheck, LaunchVerb, NodeCounts, PlanChanged, PlanDocument, PlanPage, PlanPageSection, PlanResult, PlanWarning, QueueEntry, QueueWait, Run, RunDetail, RunListQuery, RunNode, RunNodeStatus, RunRow, RunRowPage, RunRowQuery, RunTabCounts, RunEvent, RunEventLevel, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostGroup, CostSummary, NodeBuildCost } from './types/operate'; +import type { AdhocRunCheck, LaunchVerb, NodeCounts, NodeKind, PlanChanged, PlanDocument, PlanPage, PlanPageSection, PlanResult, PlanWarning, QueueEntry, QueueWait, Run, RunDetail, RunListQuery, RunNode, RunNodeStatus, RunRow, RunRowPage, RunRowQuery, RunTabCounts, RunEvent, RunEventCheck, RunEventLevel, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostGroup, CostSummary, NodeBuildCost } from './types/operate'; import { RECALL_EVENT_TYPES, SCHEDULER_FACTS } from './types/operate'; type Wire = components['schemas']; @@ -137,7 +137,8 @@ function countsOf(wire: Wire['RunRecord']): NodeCounts { success: n('success'), warn: n('warn'), failed: n('failed') + n('cancelled'), - skipped: n('skipped'), + skipped: n('skipped') + n('not_run'), + notRun: n('not_run'), running: n('running'), pending: n('pending') }; @@ -245,7 +246,7 @@ function rowOf(run: Run, wire: Wire['RunRecord']): RunRow { lostContactLimitSeconds: 0, cancelRequestedAt: isActiveRun(run.status) ? (wire.cancel_requested_at ?? null) : null, selection: run.kind === 'adhoc' ? wire.selection_json : [], - rerunFromFailureCount: (wire.node_counts_json.failed ?? 0) + c.skipped + rerunFromFailureCount: UNFINISHED_NODE_STATUSES.reduce((sum, status) => sum + (wire.node_counts_json[status] ?? 0), 0) }; } @@ -326,10 +327,20 @@ function nodeStatus(status: string): RunNodeStatus { return (['pending', 'running', 'success', 'warn', 'failed', 'skipped', 'cancelled'] as const).find((s) => s === status) ?? 'not_run'; } +const MODEL_KINDS = ['view', 'table', 'incremental'] as const; +const OTHER_KINDS = ['source', 'loader', 'seed', 'asset', 'udf', 'table_fn'] as const; + +/** A run node's kind: a model's by its materialization in the run's snapshot, anything else's by its key. */ +export function nodeKindOf(nodeKey: string, materialization: string | null | undefined): NodeKind | null { + const prefix = nodeKey.slice(0, nodeKey.indexOf(':')); + if (prefix === 'model') return MODEL_KINDS.find((k) => k === materialization) ?? null; + return OTHER_KINDS.find((k) => k === prefix) ?? null; +} + export function toRunNode(wire: Wire['RunNodeRecord'], run: Run): RunNode { return { nodeKey: wire.node_key, - kind: null, + kind: nodeKindOf(wire.node_key, wire.materialization), runId: run.id, jobKey: run.jobKey, status: nodeStatus(wire.status), @@ -337,8 +348,12 @@ export function toRunNode(wire: Wire['RunNodeRecord'], run: Run): RunNode { startedAt: wire.started_at ?? null, endedAt: wire.ended_at ?? null, rowsAffected: wire.rows_affected ?? null, + tableRows: wire.table_rows ?? null, + rowsSoFar: wire.rows_so_far ?? null, + noChangeReason: wire.no_change_reason ?? null, errorCode: wire.error_code ?? null, - errorMessage: null, + // The one error the list carries; any other is an audited read of that node's error. + errorMessage: wire.missing_secret ?? null, errorLocation: null, errorDetail: null, skippedBecauseOf: wire.skipped_because_of ? { nodeKey: wire.skipped_because_of, runId: run.id, jobKey: run.jobKey } : null, @@ -348,7 +363,7 @@ export function toRunNode(wire: Wire['RunNodeRecord'], run: Run): RunNode { /** * A run's detail from the listing and the nodes of the run and its child runs; parts with no server source stay empty. - * Rerun from failure covers failed and skipped nodes only, as the server does; cancelled nodes need a full rerun. + * Rerun from failure covers failed, cancelled, skipped and not-run nodes, as the server does. */ export function runDetailOf(run: Run, wire: Wire['RunRecord'], listed: Run[], nodes: RunNode[]): RunDetail { const byId = new Map(listed.map((r) => [r.id, r])); @@ -377,7 +392,7 @@ export function runDetailOf(run: Run, wire: Wire['RunRecord'], listed: Run[], no : null, selection: wire.selection_json, waits: [], - rerunFromFailureNodes: nodes.filter((n) => n.status === 'failed' || n.status === 'skipped').map((n) => n.nodeKey), + rerunFromFailureNodes: nodes.filter((n) => isUnfinishedNode(n.status)).map((n) => n.nodeKey), rerunOf: run.rerunOfRunId ? (byId.get(run.rerunOfRunId) ?? null) : null, reruns: listed.filter((r) => r.rerunOfRunId === run.id) }; @@ -452,7 +467,21 @@ export function toRunEvent(wire: Wire['RunEventRecord'], runId: string): RunEven nodeKey: recallNodeKey(wire), statementId: wire.statement_id ?? null, attempt: null, - message + message, + check: type === 'audit_completed' ? checkOf(wire) : null + }; +} + +const CHECK_OUTCOMES: Record = { pass: 'passed', warn: 'warned', error: 'failed' }; + +/** A check result's name, outcome and rows from its event; a result with no name recorded is named by its outcome. */ +export function checkOf(wire: Wire['RunEventRecord']): RunEventCheck { + return { + name: wire.check_name ?? wire.outcome ?? 'check', + outcome: CHECK_OUTCOMES[wire.outcome ?? ''] ?? 'skipped', + rows: wire.check_rows ?? null, + bindingKey: wire.check_binding_key ?? null, + resultId: wire.check_result_id ?? null }; } diff --git a/ui/src/lib/api/http-service-accounts.test.ts b/ui/src/lib/api/http-service-accounts.test.ts new file mode 100644 index 0000000000..b8d8b111c0 --- /dev/null +++ b/ui/src/lib/api/http-service-accounts.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { toIssuedKey, toServiceAccount } from './http-service-accounts'; + +const key = (prefix: string, expires_at: string | null = null) => ({ + key_id: `k-${prefix}`, + prefix, + origin: 'issued' as const, + created_at: '2026-11-01T00:00:00Z', + created_by: null, + last_used_at: null, + expires_at +}); + +const account = { + principal_id: 'p-orders-deploy', + name: 'orders-deploy', + description: null, + role: null, + created_at: '2026-11-01T00:00:00Z', + created_by: 'ada', + disabled_at: '2026-11-02T00:00:00Z', + last_used_at: null, + keys: [key('sqbk_Q7m2xT'), key('sqbk_b81LkD', '2026-11-21T12:00:00Z')] +}; + +describe('service accounts', () => { + it('keeps the server order of keys, a missing role and who made it, and reads disabled from its time', () => { + const shown = toServiceAccount(account); + expect([shown.kind, shown.role, shown.createdBy, shown.disabled]).toEqual(['service', null, 'ada', true]); + expect(shown.keys.map((k) => [k.prefix, k.expiresAt, k.createdBy])).toEqual([ + ['sqbk_Q7m2xT', null, null], + ['sqbk_b81LkD', '2026-11-21T12:00:00Z', null] + ]); + }); + + it('returns the key that is shown only once with its account', () => { + const issued = toIssuedKey({ account, key: 'sqbk_secret' }); + expect([issued.secret, issued.token.name]).toEqual(['sqbk_secret', 'orders-deploy']); + }); +}); diff --git a/ui/src/lib/api/http-service-accounts.ts b/ui/src/lib/api/http-service-accounts.ts new file mode 100644 index 0000000000..5c8eb186a2 --- /dev/null +++ b/ui/src/lib/api/http-service-accounts.ts @@ -0,0 +1,37 @@ +import type { components } from '$control/schema.d.ts'; +import type { IssuedToken, ServiceAccount, ServiceAccountKey } from './types/platform'; + +type Wire = components['schemas']; + +function toKey(wire: Wire['ServiceKeySummary']): ServiceAccountKey { + return { + id: wire.key_id, + prefix: wire.prefix, + createdAt: wire.created_at, + createdBy: wire.created_by ?? null, + lastUsedAt: wire.last_used_at ?? null, + expiresAt: wire.expires_at ?? null, + origin: wire.origin + }; +} + +/** A service account as the UI shows it; the server lists its working keys, the current one first. */ +export function toServiceAccount(wire: Wire['ServiceAccountSummary']): ServiceAccount { + return { + kind: 'service', + name: wire.name, + displayName: wire.name, + description: wire.description ?? null, + role: wire.role ?? null, + createdAt: wire.created_at, + createdBy: wire.created_by ?? null, + lastUsedAt: wire.last_used_at ?? null, + disabled: wire.disabled_at != null, + keys: wire.keys.map(toKey) + }; +} + +/** A key the server returns only this once, with the account it belongs to. */ +export function toIssuedKey(wire: Wire['IssuedServiceKey']): IssuedToken { + return { token: toServiceAccount(wire.account), secret: wire.key }; +} diff --git a/ui/src/lib/api/index.ts b/ui/src/lib/api/index.ts index 922573e865..c435e8b1d5 100644 --- a/ui/src/lib/api/index.ts +++ b/ui/src/lib/api/index.ts @@ -63,8 +63,8 @@ async function loadRecording(): Promise { * adjust it for demos, `?awkward` stretches every list to thousands of rows with very long * names, for the layout test, `?calm` reports nothing needing attention, `?large` swaps in a catalog the size of a real project, `?huge` one * of about 10,000 nodes in nested folders, for the Overview's and the folder view's performance budgets, - * `?secrets` runs the location without the orders API's key (`?secrets=sink` also without a sink's secret), `?still` keeps runs from advancing on their own, and `?signin=password` signs people in with - * passwords instead of SSO. + * `?secrets` runs the location without the orders API's key (`?secrets=sink` also without a sink's secret), `?still` keeps runs from advancing on their own, `?signin=password` signs people in with + * passwords instead of SSO, and `?serviceaccounts=none` starts with no service accounts. */ export function createClient( search: URLSearchParams, @@ -87,6 +87,8 @@ export function createClient( connection: LIVE.find((l) => l === live), still: search.has("still"), signIn: search.get("signin") === "password" ? "password" : undefined, + serviceAccounts: + search.get("serviceaccounts") === "none" ? "none" : undefined, }); // `?summary`: the large project with a plan shaped like a large real one's summary (CHI-1563). const summary = search.has("summary"); diff --git a/ui/src/lib/api/mock/access.ts b/ui/src/lib/api/mock/access.ts index b9c01ba072..d43b706a53 100644 --- a/ui/src/lib/api/mock/access.ts +++ b/ui/src/lib/api/mock/access.ts @@ -121,6 +121,7 @@ const PLAIN: Record = { 'sensor.reset_cursor': 'reset where a sensor is up to', 'run.adhoc': 'run sqb commands on any selection of nodes', 'connection.test': 'test warehouse connections', + 'location.republish': 'republish locations', 'plan.preview': 'preview build plans', 'location.manage': 'manage locations', 'user.manage': 'manage people', diff --git a/ui/src/lib/api/mock/big-output.ts b/ui/src/lib/api/mock/big-output.ts new file mode 100644 index 0000000000..e9c5d888e0 --- /dev/null +++ b/ui/src/lib/api/mock/big-output.ts @@ -0,0 +1,267 @@ +// A node that printed about 2 million lines (prototype, CHI-1597), and the server's paging over it. +// Line N is computed from N, never stored, so the mock pages, searches and indexes the way the output +// store would without holding the output anywhere: the browser only ever sees a page. + +import type { NodeOutputIndex, NodeOutputLevel, NodeOutputLine, NodeOutputPage, NodeOutputRow, NodeOutputSearch, RunNode } from '../types'; + +export const BIG_NODE = 'notebook_runner'; +export const BIG_TOTAL = 2_031_847; +/** Lines a second while it runs, for a node still printing. */ +export const BIG_RATE = 9_000; +const CELLS = 48; +const CELL = Math.floor(BIG_TOTAL / CELLS); +const NAMES = ['load_inputs', 'clean_orders', 'join_customers', 'feature_window', 'train_split', 'score_batch']; + +const cellOf = (n: number) => Math.min(CELLS - 1, Math.floor((n - 1) / CELL)); +const cellLen = (c: number) => (c === CELLS - 1 ? BIG_TOTAL - CELL * (CELLS - 1) : CELL); +/** Where each cell's warning sits, and the two cells with an error. */ +const warnAt = (c: number) => 1_200 + ((c * 7_919) % 30_000); +const ERROR_CELLS = new Set([17, 31]); +const errorAt = (c: number) => 20_000 + c * 13; + +/** Line `n` (1-based) of the node's output. */ +export function bigLine(n: number): NodeOutputLine { + const c = cellOf(n); + const k = n - 1 - c * CELL; + const len = cellLen(c); + const name = `${NAMES[c % NAMES.length]}_${String(c + 1).padStart(2, '0')}`; + const out = (text: string, stream: 'stdout' | 'stderr' = 'stdout', level: NodeOutputLevel = 'info'): NodeOutputLine => ({ n, stream, text, level }); + if (k === 0) return out(`[cell ${c + 1}/${CELLS}] ▶ ${name}`); + if (k === 1) return out(` reading partition date=2026-11-${String(1 + (c % 20)).padStart(2, '0')} (${len - 5} batches)`); + if (k === warnAt(c)) return out(`WARNING: cell ${c + 1}: ${c % 2 ? 'skew detected in batch' : 'slow batch'} ${k - 1} (${2 + (c % 5)}.${c % 10}s)`, 'stderr', 'warn'); + if (ERROR_CELLS.has(c) && k === errorAt(c)) return out(`ERROR: cell ${c + 1}: worker 3 lost during batch ${k - 1}; retrying from checkpoint`, 'stderr', 'error'); + if (k === len - 3) return out(` ✓ cell ${c + 1} done in ${40 + (c % 17)}s`); + if (k === len - 2) return out(` wrote ${1000 + ((c * 37) % 9000)} rows to analytics.notebook_${name}`); + if (k === len - 1) return out(''); + return out(` batch ${k - 1}/${len - 5} rows=${(k * 17) % 5000} ${3 + ((k * 7) % 40)}ms`); +} + +/** A cell's lines that are not progress: its header, warning, error and closing lines, as offsets. */ +function specials(c: number): number[] { + const len = cellLen(c); + return [0, 1, warnAt(c), ...(ERROR_CELLS.has(c) ? [errorAt(c)] : []), len - 3, len - 2, len - 1].sort((a, b) => a - b); +} + +/** + * How many similar lines run from line `n` in `step`'s direction: the progress lines between two of a + * cell's other lines read the same but for their numbers. Worked out, not scanned, as an index would. + */ +function similarRun(n: number, step: 1 | -1, available: number): number { + const c = cellOf(n); + const k = n - 1 - c * CELL; + const sp = specials(c); + if (sp.includes(k)) return 1; + const end = step > 0 ? sp.find((x) => x > k)! : [...sp].reverse().find((x) => x < k)!; + const count = Math.abs(end - k); + return step > 0 ? Math.min(count, available - n + 1) : Math.min(count, n); +} + +function notebookMarks(available: number): NodeOutputIndex['marks'] { + const marks: NodeOutputIndex['marks'] = []; + for (let c = 0; c < CELLS; c++) { + const base = c * CELL + 1; + const w = base + warnAt(c); + if (w <= available) marks.push({ line: w, level: 'warn', text: bigLine(w).text }); + if (ERROR_CELLS.has(c) && base + errorAt(c) <= available) marks.push({ line: base + errorAt(c), level: 'error', text: bigLine(base + errorAt(c)).text }); + } + return marks.sort((a, b) => a.line - b.line); +} + +// ---- output sources: a node's printed lines, computed by line number ---- + +/** A node's whole output, as the output store and its index would serve it. */ +export type OutputSource = { + total: number; + /** Lines a second while it runs. */ + rate: number; + line(n: number): NodeOutputLine; + /** How many similar lines run from `n` in `step`'s direction. */ + similarRun(n: number, step: 1 | -1, available: number): number; + /** Error and warning lines, from the index. */ + marks(available: number): NodeOutputIndex['marks']; + /** Every stderr line's number. */ + stderrLines(available: number): number[]; +}; + +const NOTEBOOK: OutputSource = { total: BIG_TOTAL, rate: BIG_RATE, line: bigLine, similarRun, marks: notebookMarks, stderrLines: (available) => notebookMarks(available).map((m) => m.line) }; + +/** Lines that read the same but for their numbers: one shape. */ +const shapeOf = (l: NodeOutputLine) => `${l.stream}|${l.text.replace(/\d+/g, '#')}`; + +/** A small output's own source: similar runs and marks found by reading it, which is cheap at its size. */ +function smallSource(lines: (n: number) => NodeOutputLine, total: number, rate: number): OutputSource { + return { + total, + rate, + line: lines, + similarRun(n, step, available) { + const shape = shapeOf(lines(n)); + let count = 1; + while (n + step * count >= 1 && n + step * count <= available && shapeOf(lines(n + step * count)) === shape) count++; + return count; + }, + marks(available) { + const out: NodeOutputIndex['marks'] = []; + for (let n = 1; n <= available; n++) { + const l = lines(n); + if (l.level !== 'info') out.push({ line: n, level: l.level, text: l.text }); + } + return out; + }, + stderrLines(available) { + const out: number[] = []; + for (let n = 1; n <= available; n++) if (lines(n).stream === 'stderr') out.push(n); + return out; + } + }; +} + +// A Python task that prints a few thousand lines, then fails with a chained pandas KeyError (CHI-1591). +export const V2_NODE = 'score_customers_v2'; +const V2_PRINTED = 2_960; +export const V2_TRACEBACK = [ + 'Traceback (most recent call last):', + ' File "/app/.venv/lib/python3.12/site-packages/pandas/core/indexes/base.py", line 3805, in get_loc', + ' return self._engine.get_loc(casted_key)', + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^', + ' File "index.pyx", line 167, in pandas._libs.index.IndexEngine.get_loc', + ' File "index.pyx", line 196, in pandas._libs.index.IndexEngine.get_loc', + ' File "pandas/_libs/hashtable_class_helper.pxi", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item', + ' File "pandas/_libs/hashtable_class_helper.pxi", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item', + "KeyError: 'customer_segment'", + '', + 'The above exception was the direct cause of the following exception:', + '', + 'Traceback (most recent call last):', + ' File "/app/.venv/lib/python3.12/site-packages/sqlbuild/executor/task.py", line 142, in run_task', + ' result = self._call(node, ctx)', + ' ^^^^^^^^^^^^^^^^^^^^^', + ' File "/app/.venv/lib/python3.12/site-packages/sqlbuild/executor/task.py", line 201, in _call', + ' return node.fn(ctx)', + ' ^^^^^^^^^^^^', + ' File "/app/models/ml/score_customers_v2.py", line 41, in score_customers_v2', + ' features = build_features(customers, segments)', + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^', + ' File "/app/models/ml/score_customers_v2.py", line 26, in build_features', + ' joined["segment_weight"] = joined["customer_segment"].map(SEGMENT_WEIGHTS)', + ' ~~~~~~^^^^^^^^^^^^^^^^^^^^', + ' File "/app/.venv/lib/python3.12/site-packages/pandas/core/frame.py", line 4102, in __getitem__', + ' indexer = self.columns.get_loc(key)', + ' ^^^^^^^^^^^^^^^^^^^^^^^^^', + ' File "/app/.venv/lib/python3.12/site-packages/pandas/core/indexes/base.py", line 3812, in get_loc', + ' raise KeyError(key) from err', + "KeyError: 'customer_segment'" +]; +export const V2_TOTAL = V2_PRINTED + V2_TRACEBACK.length; +function v2Line(n: number): NodeOutputLine { + const out = (text: string, stream: 'stdout' | 'stderr' = 'stdout', level: NodeOutputLevel = 'info'): NodeOutputLine => ({ n, stream, text, level }); + if (n > V2_PRINTED) { + const text = V2_TRACEBACK[n - V2_PRINTED - 1] ?? ''; + return out(text, 'stderr', text.startsWith('KeyError') ? 'error' : 'info'); + } + if (n === 1) return out('Loading customers from analytics.dim_customers'); + if (n === 2) return out('Loaded 48,120 customers, 31 columns'); + if (n === 3) return out('Loading segments from analytics.customer_segments'); + if (n === V2_PRINTED) return out('Building features for 48,120 customers'); + if (n === V2_PRINTED - 1) return out('Scored 48,120 customers with model churn_v2 (rev 14)'); + return out(` scoring batch ${n - 3}/${V2_PRINTED - 5} customers=${16 + ((n * 7) % 9)} ${2 + ((n * 13) % 30)}ms`); +} + +export const OUTPUT_SOURCES: Record = { + [BIG_NODE]: NOTEBOOK, + [V2_NODE]: smallSource(v2Line, V2_TOTAL, 900) +}; + +export function bigIndex(nodeKey: string, available: number, live: boolean): NodeOutputIndex { + const src = OUTPUT_SOURCES[nodeKey]; + const marks = src.marks(available); + const stderr = src.stderrLines(available).length; + return { total: available, stdout: available - stderr, stderr, bytes: Math.round(available * 46.3), marks, live }; +} + +export type PageAt = { from: number; rows: number; direction: 'forward' | 'backward'; collapse: boolean; stream?: 'all' | 'stdout' | 'stderr'; around?: number }; + +/** + * Up to `rows` rows from line `from`, forwards, or backwards ending just before `from`; similar lines + * folded when `collapse`, except the block holding `around` (a jump's target), which opens around it. + * `stream` keeps only stdout or stderr lines, keeping their line numbers. + */ +export function bigPage(nodeKey: string, available: number, at: PageAt): NodeOutputPage { + const src = OUTPUT_SOURCES[nodeKey]; + const step = at.direction === 'forward' ? 1 : -1; + const rows: NodeOutputRow[] = []; + if (at.stream === 'stderr') { + // stderr lines are the index's marks: read them from the index, not by walking the output. + const lines = src.stderrLines(available); + const picked = step > 0 ? lines.filter((l) => l >= at.from).slice(0, at.rows) : lines.filter((l) => l < at.from).slice(-at.rows); + for (const l of picked) rows.push({ kind: 'line', line: src.line(l) }); + } else { + let n = step > 0 ? Math.max(1, at.from) : Math.min(available, at.from - 1); + while (rows.length < at.rows && n >= 1 && n <= available) { + const first = src.line(n); + if (at.stream === 'stdout' && first.stream === 'stderr') { + n += step; + continue; + } + let count = at.collapse ? src.similarRun(n, step, available) : 1; + const lo = step > 0 ? n : n - count + 1; + if (count >= 4 && at.around != null && at.around >= lo && at.around < lo + count) { + // The jump's target is inside this block: fold what comes before it, then show its lines. + const before = step > 0 ? at.around - 3 - n : n - (at.around + 3); + if (before >= 4) { + rows.push({ kind: 'similar', from: step > 0 ? n : at.around + 4, count: before, sample: src.line(step > 0 ? n : at.around + 4) }); + n += step * before; + } + const near = Math.min(7, Math.abs(n - (step > 0 ? at.around + 4 : at.around - 4))); + for (let i = 0; i < near && n >= 1 && n <= available; i++, n += step) rows.push({ kind: 'line', line: src.line(n) }); + continue; + } + if (count >= 4) rows.push({ kind: 'similar', from: lo, count, sample: src.line(lo) }); + else { + count = 1; + rows.push({ kind: 'line', line: first }); + } + n += step * count; + } + } + if (step < 0) rows.reverse(); + const firstLine = (r: NodeOutputRow) => (r.kind === 'line' ? r.line.n : r.from); + const lastLine = (r: NodeOutputRow) => (r.kind === 'line' ? r.line.n : r.from + r.count - 1); + return { total: available, from: rows.length ? firstLine(rows[0]) : at.from, to: rows.length ? lastLine(rows[rows.length - 1]) + 1 : at.from, rows }; +} + +// A search is a scan over every line; its hits are kept for the next and previous match, as the server +// would keep a search's result while someone steps through it. +const searches = new Map(); +export function bigSearch(nodeKey: string, available: number, query: string, from: number, direction: 'forward' | 'backward'): NodeOutputSearch { + const src = OUTPUT_SOURCES[nodeKey]; + const q = query.toLowerCase(); + if (!q) return { count: 0, line: null, rank: null }; + const key = `${nodeKey}|${available}|${q}`; + let hits = searches.get(key); + if (!hits) { + hits = []; + for (let n = 1; n <= available; n++) if (src.line(n).text.toLowerCase().includes(q)) hits.push(n); + searches.clear(); + searches.set(key, hits); + } + const line = direction === 'forward' ? (hits.find((h) => h >= from) ?? hits[0] ?? null) : ([...hits].reverse().find((h) => h <= from) ?? hits[hits.length - 1] ?? null); + return { count: hits.length, line, rank: line == null ? null : hits.indexOf(line) + 1 }; +} + +/** + * Where the server streams the whole output as a file. The mock has no file server, so its link opens a + * short note in place of the file. + */ +export function bigDownloadUrl(runId: string, nodeKey: string, available: number): string { + const note = `Mock: the server streams ${runId}'s ${nodeKey} output here, ${available.toLocaleString('en-GB')} lines, as a file.\n`; + return URL.createObjectURL(new Blob([note], { type: 'text/plain' })); +} + +/** How many lines the node has printed by `now`: all of them once it finished, else so far. */ +export function bigAvailable(n: RunNode, now: number): { available: number; live: boolean } | null { + const src = OUTPUT_SOURCES[n.nodeKey]; + if (!src || !n.startedAt) return null; + if (n.status !== 'running') return { available: src.total, live: false }; + return { available: Math.max(1, Math.min(src.total - 1, Math.floor(((now - Date.parse(n.startedAt)) / 1000) * src.rate))), live: true }; +} diff --git a/ui/src/lib/api/mock/build-fixtures.ts b/ui/src/lib/api/mock/build-fixtures.ts index b3079b91a4..7a918cacab 100644 --- a/ui/src/lib/api/mock/build-fixtures.ts +++ b/ui/src/lib/api/mock/build-fixtures.ts @@ -44,6 +44,26 @@ export type NodeSpec = { const c = (name: string, type: string, description: string, audits: string[] = [], expr?: string): ColumnSpec => ({ name, type, description, audits, expr }); export const NODE_SPECS: Record = { + // Prototype (CHI-1591) nodes. + stg_sessions: { materialization: 'view', description: 'Storefront sessions, one row each.', schema: 'ANALYTICS', columns: [c('session_id', 'bigint', 'Session', ['not_null', 'unique']), c('customer_id', 'bigint', 'Customer', ['not_null']), c('channel', 'varchar', 'Channel', ['accepted_values']), c('started_at', 'timestamp', 'Started', ['not_null'])] }, + fct_payment_daily: { materialization: 'table', description: 'Payments by day and method.', schema: 'ANALYTICS', columns: [c('payment_id', 'bigint', 'Payment', ['not_null']), c('payment_day', 'date', 'Day', ['unique']), c('amount_cents', 'bigint', 'Amount', ['not_null']), c('status', 'varchar', 'Status', ['accepted_values']), c('method', 'varchar', 'Method', ['not_null'])] }, + fct_order_lines: { materialization: 'table', description: 'One row per order line, with its payment.', schema: 'ANALYTICS', columns: [c('payment_id', 'bigint', 'Payment', ['not_null']), c('order_id', 'bigint', 'Order', ['unique']), c('order_line_id', 'bigint', 'Order line', ['not_null']), c('product_id', 'bigint', 'Product', ['not_null']), c('status', 'varchar', 'Status', ['accepted_values'])] }, + fct_refunds: { materialization: 'table', description: 'Refunds, one row per refunded order.', schema: 'ANALYTICS', columns: [c('order_id', 'bigint', 'Order', ['unique']), c('payment_id', 'bigint', 'Payment', ['not_null']), c('status', 'varchar', 'Status', ['accepted_values']), c('reason', 'varchar', 'Reason', ['not_null']), c('refund_id', 'bigint', 'Refund', ['not_null', 'unique']), c('amount_cents', 'bigint', 'Amount', ['not_null']), c('refunded_at', 'timestamp', 'Refunded', ['not_null']), c('customer_id', 'bigint', 'Customer', ['not_null']), c('currency', 'varchar', 'Currency', ['accepted_values'])] }, + stg_cost_prices: { materialization: 'view', description: 'Unit cost of each product, by day.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null']), c('cost_cents', 'bigint', 'Unit cost in cents', ['not_null'])] }, + fct_order_margin: { materialization: 'table', description: 'Margin of each order line: revenue less unit cost.', schema: 'ANALYTICS', columns: [c('order_line_id', 'bigint', 'Order line', ['not_null', 'unique']), c('margin_cents', 'bigint', 'Margin in cents'), c('margin_pct', 'double', 'Margin as a share of revenue', ['not_null'])] }, + agg_margin_daily: { materialization: 'incremental', description: 'Margin by day.', schema: 'ANALYTICS', columns: [c('day', 'date', 'Day', ['not_null', 'unique']), c('margin_cents', 'bigint', 'Margin in cents')] }, + rpt_margin_weekly: { materialization: 'table', description: 'Margin by week, for the finance review.', schema: 'ANALYTICS', columns: [c('week', 'date', 'Week', ['not_null', 'unique'])] }, + rpt_margin_by_category: { materialization: 'table', description: 'Margin by product category.', schema: 'ANALYTICS', columns: [c('category', 'varchar', 'Category', ['not_null'])] }, + stg_inventory: { materialization: 'view', description: 'Stock counts from the warehouse system.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null']), c('on_hand', 'bigint', 'Units on hand', ['not_null'])] }, + stg_products: { materialization: 'view', description: 'Products from the catalogue.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null', 'unique'])] }, + dim_products: { materialization: 'table', description: 'One row per product.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null', 'unique']), c('category', 'varchar', 'Category', ['not_null'])] }, + fct_stock_levels: { materialization: 'incremental', description: 'Stock level of each product, by hour.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null']), c('on_hand', 'bigint', 'Units on hand')] }, + agg_stock_by_day: { materialization: 'table', description: 'Stock by day.', schema: 'ANALYTICS', columns: [c('day', 'date', 'Day', ['not_null'])] }, + rpt_low_stock: { materialization: 'table', description: 'Products below their reorder point.', schema: 'ANALYTICS', columns: [c('product_id', 'bigint', 'Product', ['not_null'])] }, + stg_shipping: { materialization: 'view', description: 'Shipments from the carrier feed.', schema: 'ANALYTICS', columns: [c('shipment_id', 'bigint', 'Shipment', ['not_null', 'unique'])] }, + fct_shipments: { materialization: 'incremental', description: 'One row per shipment, with its order.', schema: 'ANALYTICS', columns: [c('shipment_id', 'bigint', 'Shipment', ['not_null', 'unique']), c('order_id', 'bigint', 'Order', ['not_null'])] }, + agg_delivery_times: { materialization: 'table', description: 'Delivery times by carrier and day.', schema: 'ANALYTICS', columns: [c('day', 'date', 'Day', ['not_null'])] }, + rpt_late_deliveries: { materialization: 'table', description: 'Orders delivered after their promised date.', schema: 'ANALYTICS', columns: [c('order_id', 'bigint', 'Order', ['not_null'])] }, raw__customers: { materialization: null, description: 'Customer records replicated from the shop database.', @@ -175,6 +195,106 @@ export const NODE_SPECS: Record = { }; export const PYTHON_SOURCE: Record = { + score_customers_v2: { + file: 'models/ml/score_customers_v2.py', + source: `import numpy as np +import pandas as pd +from sqlbuild.tasks import task + +from shop.models import churn_model + +SEGMENT_WEIGHTS = { + "loyal": 0.6, + "regular": 1.0, + "lapsing": 1.4, + "new": 1.1, +} + + +def build_features(customers: pd.DataFrame, segments: pd.DataFrame) -> pd.DataFrame: + \"\"\"Joins each customer to their segment and derives the model's features.\"\"\" + joined = customers.merge( + segments, + how="left", + left_on="customer_id", + right_on="customer_id", + suffixes=("", "_seg"), + ) + # The segments table renamed customer_segment to segment in rev 14. + joined["orders_per_month"] = joined["orders"] / joined["tenure_months"].clip(lower=1) + joined["segment_weight"] = joined["customer_segment"].map(SEGMENT_WEIGHTS) + return joined[["customer_id", "orders_per_month", "lifetime_value", "segment_weight"]] + + +@task(upstream=["dim_customers"]) +def score_customers_v2(ctx): + \"\"\"Scores churn risk with model churn_v2, weighting by customer segment.\"\"\" + customers = ctx.query('SELECT * FROM __ref("dim_customers")').to_pandas() + print(f"Loaded {len(customers):,} customers, {len(customers.columns)} columns") + segments = ctx.query("SELECT * FROM analytics.customer_segments").to_pandas() + model = churn_model("churn_v2") + for i, batch in enumerate(batches(customers, size=16)): + print(f" scoring batch {i}") + model.score(batch) + + features = build_features(customers, segments) + ctx.write("customer_scores_v2", model.predict(features))` + }, + notebook_runner: { + file: 'models/ml/notebook_runner.py', + source: `from sqlbuild.tasks import task + +from shop.notebooks import run_notebook + + +@task(upstream=["fact_orders"]) +def notebook_runner(ctx): + \"\"\"Runs the churn features notebook, cell by cell. It prints every batch.\"\"\" + ctx.log.info("Running notebook churn_features.ipynb (48 cells)") + result = run_notebook("notebooks/churn_features.ipynb", on_retry=lambda cell: ctx.log.warning(f"cell {cell} retried after worker loss")) + ctx.log.info(f"Notebook finished: {result.cells} cells, {result.rows_written:,} rows written")` + }, + raw_events: { + file: 'models/ingest/raw_events.py', + source: `import logging + +from sqlbuild.loaders import loader +from sqlbuild.executor.load.models import LoaderContext + +from shop.events_api import fetch_page + +log = logging.getLogger("shop.events") + + +@loader(cursor="occurred_at", strategy="append") +def raw_events(ctx: LoaderContext): + """Storefront events from the events API, paged since the last cursor.""" + page = 1 + while True: + rows = fetch_page(since=ctx.current_cursor_value, page=page) + if not rows: + return + print(f"Page {page}: {len(rows):,} events") + yield rows + page += 1` + }, + score_customers: { + file: 'models/ml/score_customers.py', + source: `import pandas as pd +from sqlbuild.tasks import task + + +@task(upstream=["dim_customers"]) +def score_customers(ctx): + """Scores each customer's churn risk and writes it back.""" + customers = ctx.query('SELECT * FROM __ref("dim_customers")').to_pandas() + print(f"Loaded {len(customers):,} customers") + features = customers[["orders", "lifetime_value"]] + features = features.fillna(method="ffill") + customers["churn_risk"] = model().predict_proba(features)[:, 1] + ctx.write("customer_scores", customers[["customer_id", "churn_risk"]]) + print(f"Scored {len(customers):,} customers")` + }, raw__orders: { file: 'python/raw__orders.py', source: `from sqlbuild.loaders import loader diff --git a/ui/src/lib/api/mock/fixtures.ts b/ui/src/lib/api/mock/fixtures.ts index 0d21ca59a8..f7584d372a 100644 --- a/ui/src/lib/api/mock/fixtures.ts +++ b/ui/src/lib/api/mock/fixtures.ts @@ -6,7 +6,7 @@ import { CAPABILITIES } from '../types'; const MIN = 60_000; -const OPERATE: Capability[] = ['view', 'view.sql', 'job.run', 'run.cancel', 'run.rerun', 'trigger.toggle', 'sensor.reset_cursor']; +const OPERATE: Capability[] = ['view', 'view.sql', 'job.run', 'run.cancel', 'run.rerun', 'trigger.toggle', 'sensor.reset_cursor', 'location.republish']; const DEVELOP: Capability[] = [...OPERATE, 'view.evidence', 'run.rewrite_history', 'run.adhoc', 'connection.test', 'plan.preview']; /** Mock-only approximation of the built-in roles; the server owns the real grants. */ diff --git a/ui/src/lib/api/mock/missing-secrets.ts b/ui/src/lib/api/mock/missing-secrets.ts index 9fdf821a05..e2bae6f5ce 100644 --- a/ui/src/lib/api/mock/missing-secrets.ts +++ b/ui/src/lib/api/mock/missing-secrets.ts @@ -84,7 +84,7 @@ function withMissingKeyItem(overview: Overview | null, scope: Scope): Overview | active: true, locationId: scope.locationId, subject: null, - message: "orders_api is missing ORDERS_API_KEY in the location's environment, so runs of the node that uses it stop before the warehouse." + message: "orders_api is missing ORDERS_API_KEY in the location's environment, so runs of raw_orders stop before the warehouse." }; return { ...overview, attention: [{ kind: 'platform_event', event }, ...overview.attention] }; } diff --git a/ui/src/lib/api/mock/mock-client.ts b/ui/src/lib/api/mock/mock-client.ts index e3bd2fbcb7..c3d279dbdd 100644 --- a/ui/src/lib/api/mock/mock-client.ts +++ b/ui/src/lib/api/mock/mock-client.ts @@ -34,6 +34,10 @@ import type { RunListQuery, RunNodeError, RunOutputLine, + NodeOutputIndex, + NodeOutputPage, + NodeOutputSearch, + CheckSample, RunStatement, RunCostRow, IgnoredAuditFailure, @@ -41,7 +45,7 @@ import type { NodeBuildCost, NodeState, NodeStates, - Scope, + RepublishResult, Scope, Snapshot, SnapshotNode, Timeline, @@ -69,6 +73,8 @@ export type MockOptions = { connection?: ConnectionState; /** How people sign in (`?signin=password`); SSO by default. */ signIn?: AuthMode; + /** `none` starts with no service accounts (`?serviceaccounts=none`). */ + serviceAccounts?: 'default' | 'none'; }; /** In-memory `ApiClient` with neutral example data. Mutations persist per page load. */ @@ -96,7 +102,8 @@ export class MockApiClient implements ApiClient { latencyMs: options.latencyMs ?? 120, connection: options.connection ?? 'live', still: options.still ?? false, - signIn: options.signIn ?? 'oidc' + signIn: options.signIn ?? 'oidc', + serviceAccounts: options.serviceAccounts ?? 'default' }; this.changes.setState(this.#options.connection); this.#fixtures = createFixtures(this.#createdAt); @@ -117,6 +124,7 @@ export class MockApiClient implements ApiClient { serverVersion: '0.185.0', authMode: this.#options.signIn, user: DEMO_USER, + serviceAccounts: this.#options.serviceAccounts, locations: this.#fixtures.locations, changes: this.changes, platformEvents: () => this.#platformEvents(), @@ -300,6 +308,27 @@ export class MockApiClient implements ApiClient { return this.#operate.listRunOutput(scope, runId); } + // A node's bulk output, paged as the output store would serve it (prototype, CHI-1597). + async getNodeOutputIndex(scope: Scope, runId: string, nodeKey: string): Promise { + this.#location(scope); + return this.#operate.getNodeOutputIndex(scope, runId, nodeKey); + } + async getNodeOutputPage(scope: Scope, runId: string, nodeKey: string, at: { from: number; rows: number; direction: 'forward' | 'backward'; collapse: boolean; stream?: 'all' | 'stdout' | 'stderr'; around?: number }): Promise { + this.#location(scope); + return this.#operate.getNodeOutputPage(scope, runId, nodeKey, at); + } + async searchNodeOutput(scope: Scope, runId: string, nodeKey: string, query: string, from: number, direction: 'forward' | 'backward'): Promise { + this.#location(scope); + return this.#operate.searchNodeOutput(scope, runId, nodeKey, query, from, direction); + } + nodeOutputDownloadUrl(scope: Scope, runId: string, nodeKey: string): string { + return this.#operate.nodeOutputDownloadUrl(scope, runId, nodeKey); + } + async getCheckSample(scope: Scope, runId: string, statementId: string): Promise { + this.#location(scope); + return this.#operate.getCheckSample(scope, runId, statementId); + } + async getRunNodeError(scope: Scope, runId: string, nodeKey: string): Promise { const node = (await this.getRunDetail(scope, runId))?.nodes.find((n) => n.runId === runId && n.nodeKey === nodeKey); if (!node) throw new ApiError('node not found in this run', 404); @@ -478,6 +507,12 @@ export class MockApiClient implements ApiClient { return this.#reply(undefined); } + async republish(scope: Scope): Promise { + this.#require('location.republish'); + this.#location(scope); + return this.#reply({ state: 'published', generation: null, error: null }); + } + // ---- platform and admin: delegated to MockPlatformApi (mock/platform.ts) ---- platformHealth(...args: Parameters) { @@ -528,6 +563,24 @@ export class MockApiClient implements ApiClient { createPasswordAccount(...args: Parameters) { return this.#platform.createPasswordAccount(...args); } + listServiceAccounts(...args: Parameters) { + return this.#platform.listServiceAccounts(...args); + } + createServiceAccount(...args: Parameters) { + return this.#platform.createServiceAccount(...args); + } + rotateServiceAccountKey(...args: Parameters) { + return this.#platform.rotateServiceAccountKey(...args); + } + revokeServiceAccountKey(...args: Parameters) { + return this.#platform.revokeServiceAccountKey(...args); + } + setServiceAccountDisabled(...args: Parameters) { + return this.#platform.setServiceAccountDisabled(...args); + } + setServiceAccountRole(...args: Parameters) { + return this.#platform.setServiceAccountRole(...args); + } listRoles(...args: Parameters) { return this.#platform.listRoles(...args); } diff --git a/ui/src/lib/api/mock/mock-node-states.test.ts b/ui/src/lib/api/mock/mock-node-states.test.ts index dd8b5a8d05..87e7dcce36 100644 --- a/ui/src/lib/api/mock/mock-node-states.test.ts +++ b/ui/src/lib/api/mock/mock-node-states.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { stateOf } from '../node-states'; import type { ChangedSignal } from '../signals'; import { MockApiClient } from './mock-client'; @@ -7,6 +7,10 @@ import { LOCATION_SHOP } from './fixtures'; const SCOPE = { locationId: LOCATION_SHOP }; describe('mock node states', () => { + // The mock's live runs finish nodes by the clock, the first within two seconds, so a slow test would see a state really change. + beforeEach(() => vi.useFakeTimers({ now: Date.parse('2026-01-15T09:00:00Z'), toFake: ['Date'] })); + afterEach(() => vi.useRealTimers()); + it('answers the node-states read with the listing states at a stable version', async () => { const client = new MockApiClient({ latencyMs: 0 }); const [nodes, first] = await Promise.all([client.listCatalogNodes(SCOPE), client.listNodeStates(SCOPE)]); diff --git a/ui/src/lib/api/mock/operate-graph-selection.test.ts b/ui/src/lib/api/mock/operate-graph-selection.test.ts index 767e0d4f83..44607fcb82 100644 --- a/ui/src/lib/api/mock/operate-graph-selection.test.ts +++ b/ui/src/lib/api/mock/operate-graph-selection.test.ts @@ -23,11 +23,11 @@ describe('mock selection evaluation', () => { it('counts models of every materialization as one kind', () => { expect(mockVocabulary().kinds).toEqual([ - { value: 'asset', count: 1 }, - { value: 'loader', count: 1 }, - { value: 'model', count: 12 }, + { value: 'asset', count: 4 }, + { value: 'loader', count: 2 }, + { value: 'model', count: 31 }, { value: 'seed', count: 1 }, - { value: 'source', count: 2 } + { value: 'source', count: 6 } ]); }); }); diff --git a/ui/src/lib/api/mock/operate-graph.ts b/ui/src/lib/api/mock/operate-graph.ts index f479c0e0fc..71fdf13522 100644 --- a/ui/src/lib/api/mock/operate-graph.ts +++ b/ui/src/lib/api/mock/operate-graph.ts @@ -40,7 +40,39 @@ export const SNAPSHOT_NODES: SnapshotNode[] = [ node('daily_activity_rollup', 'incremental', 'activity', ['hourly_activity_ctx'], { cursor: 'timestamp' }), node('revenue_report', 'table', 'reporting', ['daily_revenue'], { tags: ['finance'] }), node('activity_report', 'table', 'reporting', ['hourly_activity_ctx']), - node('export_revenue_csv', 'asset', 'exports', ['revenue_report'], { tags: ['export'] }) + node('export_revenue_csv', 'asset', 'exports', ['revenue_report'], { tags: ['export'] }), + // Prototype (CHI-1591): finance, inventory and fulfillment folders, so a job run has about 30 nodes. + node('raw__cost_prices', 'source', 'sources', []), + node('raw__inventory', 'source', 'sources', []), + node('raw__products', 'source', 'sources', []), + node('raw__shipments', 'source', 'sources', []), + node('stg_cost_prices', 'view', 'finance', ['raw__cost_prices']), + node('fct_order_margin', 'table', 'finance', ['fact_orders', 'stg_cost_prices'], { tags: ['finance'] }), + node('agg_margin_daily', 'incremental', 'finance', ['fct_order_margin'], { cursor: 'timestamp', tags: ['finance'] }), + node('rpt_margin_weekly', 'table', 'finance', ['agg_margin_daily'], { tags: ['finance'] }), + node('rpt_margin_by_category', 'table', 'finance', ['agg_margin_daily', 'dim_products'], { tags: ['finance'] }), + node('stg_inventory', 'view', 'inventory', ['raw__inventory']), + node('stg_products', 'view', 'inventory', ['raw__products']), + node('dim_products', 'table', 'inventory', ['stg_products']), + node('fct_stock_levels', 'incremental', 'inventory', ['stg_inventory', 'dim_products'], { cursor: 'timestamp' }), + node('agg_stock_by_day', 'table', 'inventory', ['fct_stock_levels']), + node('rpt_low_stock', 'table', 'inventory', ['agg_stock_by_day', 'dim_products']), + node('stg_shipping', 'view', 'fulfillment', ['raw__shipments']), + node('fct_shipments', 'incremental', 'fulfillment', ['stg_shipping', 'fact_orders'], { cursor: 'timestamp' }), + node('agg_delivery_times', 'table', 'fulfillment', ['fct_shipments']), + node('rpt_late_deliveries', 'table', 'fulfillment', ['agg_delivery_times', 'dim_customers']), + // Python nodes (CHI-1591): a loader that prints its paging, and a task that warns. + node('raw_events', 'loader', 'ingest', [], { cursor: 'timestamp', path: 'models/ingest/raw_events.py' }), + node('score_customers', 'asset', 'ml', ['dim_customers'], { path: 'models/ml/score_customers.py' }), + // Several checks on one node (CHI-1591): all passing, one warning, two warnings, and a failure with warnings. + node('stg_sessions', 'view', 'staging', ['raw__customers']), + node('fct_payment_daily', 'table', 'finance', ['stg_payments']), + node('fct_order_lines', 'table', 'marts', ['stg_orders', 'stg_payments']), + node('fct_refunds', 'table', 'finance', ['stg_payments', 'fact_orders']), + // A Python task that fails with a pandas KeyError traceback after printing a few thousand lines. + node('score_customers_v2', 'asset', 'ml', ['dim_customers'], { path: 'models/ml/score_customers_v2.py' }), + // A notebook runner that prints about 2 million lines (CHI-1597). + node('notebook_runner', 'asset', 'ml', ['fact_orders'], { path: 'models/ml/notebook_runner.py' }) ]; const BY_KEY = new Map(SNAPSHOT_NODES.map((n) => [n.key, n])); @@ -150,13 +182,21 @@ function folderOf(n: SnapshotNode): string { return n.path.includes('/') ? n.path.slice(0, n.path.lastIndexOf('/')) : ''; } +/** `job:`: the job's nodes, as `operate.ts` resolves them (set there, which imports this module). */ +let jobNodesOf: (key: string) => string[] = () => []; +export function setJobResolver(resolve: (key: string) => string[]) { + jobNodesOf = resolve; +} + /** One comma part of a selector, with its own `+`; `null` when it matches nothing. */ function matchPart(part: string): Set | null { const up = part.startsWith('+'); const down = part.endsWith('+') && part.length > 1; const body = part.replace(/^\+/, '').replace(/\+$/, ''); const [type, value] = body.includes(':') ? [body.slice(0, body.indexOf(':')), body.slice(body.indexOf(':') + 1)] : ['name', body]; + const jobKeys = type === 'job' ? new Set(jobNodesOf(value)) : null; const base = SNAPSHOT_NODES.filter((n) => + jobKeys ? jobKeys.has(n.key) : type === 'tag' ? n.tags.includes(value) : type === 'kind' ? selectorKind(n) === value : type === 'path' ? folderOf(n) === value || folderOf(n).startsWith(`${value}/`) : n.key === value ); if (!base.length) return null; diff --git a/ui/src/lib/api/mock/operate-store.ts b/ui/src/lib/api/mock/operate-store.ts index b3e299ab43..523217be45 100644 --- a/ui/src/lib/api/mock/operate-store.ts +++ b/ui/src/lib/api/mock/operate-store.ts @@ -2,7 +2,9 @@ // its claims, jobs, triggers and sensors. A small loop advances live runs so // cancels, launches and claims behave like they do on the server. +import { bigAvailable, bigDownloadUrl, bigIndex, bigPage, bigSearch } from './big-output'; import { parseCommand } from '$lib/run/command'; +import { isUnfinishedNode } from '$lib/status'; import { flagSpec, VERBS } from '$lib/run/command-table'; import { ApiError } from '../client'; import type { LocalChangeBus } from '../signals'; @@ -39,6 +41,10 @@ import type { RunListQuery, RunNode, RunOutputLine, + NodeOutputIndex, + NodeOutputPage, + NodeOutputSearch, + CheckSample, RunRow, RunRowPage, RunRowQuery, @@ -97,6 +103,8 @@ import { isTerminal, liveness, sqlFor, + auditSample, + auditSql, statusReason, type RunRecord } from './run-detail'; @@ -144,6 +152,9 @@ export type OperateContext = { /** The end-to-end tests' stand-in for a plan recorded without timings: `window.__sqbPlanWithoutTimings`. */ const withoutTimings = () => typeof window !== 'undefined' && !!(window as unknown as { __sqbPlanWithoutTimings?: boolean }).__sqbPlanWithoutTimings; +/** What a rerun from failure runs, as on the server. */ +const unfinished = (n: RunNode) => isUnfinishedNode(n.status); + /** A location preview's planning steps, as the plan summary reports them. */ const MOCK_PLAN_TIMINGS: PlanTimings = { total_seconds: 10.6, @@ -214,7 +225,7 @@ export class MockOperate { lostContactLimitSeconds: PRESUMED_FAILED_MS / 1000, cancelRequestedAt: cancel && !cancel.terminatedAt ? cancel.requestedAt : null, selection: view.kind === 'adhoc' ? rec.script.select : [], - rerunFromFailureCount: nodes.filter((n) => n.status === 'failed' || n.status === 'skipped').length + rerunFromFailureCount: nodes.filter(unfinished).length }; }); const next = offset + limit < matching.length ? `c${offset + limit}` : null; @@ -332,7 +343,7 @@ export class MockOperate { }, selection: rec.script.select, waits: rec.run.status === 'queued' ? this.#queue().get(rec.run.id) ?? [] : [], - rerunFromFailureNodes: nodes.filter((n) => n.status === 'failed' || n.status === 'skipped').map((n) => n.nodeKey), + rerunFromFailureNodes: nodes.filter(unfinished).map((n) => n.nodeKey), rerunOf: rec.run.rerunOfRunId ? ((r) => (r ? this.#view(r, scope) : null))(this.#byId(rec.run.rerunOfRunId)) : null, reruns: this.#records .filter((r) => r.run.rerunOfRunId === rec.run.id) @@ -490,7 +501,41 @@ export class MockOperate { const now = Date.now(); const statement = execution(rec, this.#nodesOf(rec, now), now).statements.find((st) => st.id === statementId); if (!statement) throw new ApiError(`Unknown statement ${statementId}`, 404); - return this.#ctx.reply({ statementId, sql: statement.sqlRecorded ? sqlFor(statement.nodeKey, statement.kind, this.#ctx.target(scope)) : null }); + const target = this.#ctx.target(scope); + const sql = statement.kind === 'audit' ? auditSql(statement.nodeKey, statementId, target) : sqlFor(statement.nodeKey, statement.kind, target); + return this.#ctx.reply({ statementId, sql: statement.sqlRecorded ? sql : null }); + } + + getCheckSample(_scope: Scope, runId: string, statementId: string): Promise { + const rec = this.#require(runId); + const now = Date.now(); + const statement = execution(rec, this.#nodesOf(rec, now), now).statements.find((st) => st.id === statementId); + return this.#ctx.reply(statement?.kind === 'audit' && statement.rowsAffected ? auditSample(statement.nodeKey, statementId, statement.rowsAffected) : null); + } + + /** How much of a node's bulk output exists now (CHI-1597): only the notebook runner prints enough to page. */ + #bigOutput(runId: string, nodeKey: string): { available: number; live: boolean } | null { + const rec = this.#require(runId); + const now = Date.now(); + const n = this.#nodesOf(rec, now).find((x) => x.nodeKey === nodeKey); + return n ? bigAvailable(n, now) : null; + } + getNodeOutputIndex(_scope: Scope, runId: string, nodeKey: string): Promise { + const big = this.#bigOutput(runId, nodeKey); + return this.#ctx.reply(big ? bigIndex(nodeKey, big.available, big.live) : null); + } + getNodeOutputPage(_scope: Scope, runId: string, nodeKey: string, at: { from: number; rows: number; direction: 'forward' | 'backward'; collapse: boolean; stream?: 'all' | 'stdout' | 'stderr'; around?: number }): Promise { + const big = this.#bigOutput(runId, nodeKey); + return this.#ctx.reply(big ? bigPage(nodeKey, big.available, at) : { total: 0, from: at.from, to: at.from, rows: [] }); + } + searchNodeOutput(_scope: Scope, runId: string, nodeKey: string, query: string, from: number, direction: 'forward' | 'backward'): Promise { + const big = this.#bigOutput(runId, nodeKey); + return this.#ctx.reply(big ? bigSearch(nodeKey, big.available, query, from, direction) : { count: 0, line: null, rank: null }); + } + /** The mock has no file server: the link opens a short note where the server would stream the file. */ + nodeOutputDownloadUrl(_scope: Scope, runId: string, nodeKey: string): string { + const big = this.#bigOutput(runId, nodeKey); + return bigDownloadUrl(runId, nodeKey, big?.available ?? 0); } listRunOutput(scope: Scope, runId: string): Promise { @@ -615,14 +660,14 @@ export class MockOperate { const now = Date.now(); const affected = (rec: RunRecord) => this.#nodesOf(rec, now) - .filter((n) => (mode === 'selected' ? selectedNodes.includes(n.nodeKey) : n.status === 'failed' || n.status === 'skipped')) + .filter((n) => (mode === 'selected' ? selectedNodes.includes(n.nodeKey) : unfinished(n))) .map((n) => n.nodeKey); const user = this.#ctx.user(); const id = this.#newId(); const job = jobDef(source.run.jobKey); if (job?.kind === 'group') { const members = this.#children(source).filter((c) => mode === 'all' || affected(c).length); - if (!members.length) throw new ApiError('Nothing to rerun: no node failed or was skipped', 409); + if (!members.length) throw new ApiError('Nothing to rerun: no node failed, was cancelled, was skipped or went unreached', 409); const parent = this.#create(scope, { id, origin: 'rerun', jobKey: job.key, rerunOf: runId, by: user, select: [], exclude: [], flags: {}, nodes: [], priority: job.priority }); members.forEach((c, i) => { const nodes = mode === 'all' ? c.script.nodes : affected(c); @@ -633,7 +678,7 @@ export class MockOperate { return this.#ctx.reply(this.#view(parent, scope)); } const nodes = mode === 'all' ? source.script.nodes : affected(source); - if (!nodes.length) throw new ApiError('Nothing to rerun: no node failed or was skipped', 409); + if (!nodes.length) throw new ApiError('Nothing to rerun: no node failed, was cancelled, was skipped or went unreached', 409); const rec = this.#create(scope, { id, origin: 'rerun', @@ -818,7 +863,7 @@ export class MockOperate { const now = new Date().toISOString(); const actor = this.#ctx.user(); this.#fx.evaluations[def.name] = [ - { ...stuck, id: `eval-skip-${++this.#seq}`, outcome: 'skipped', requestedAt: now, finishedAt: now, runIds: [], skippedFor: [], failureCode: null, error: null, abandonedBecause: null, skipReason: reason, skippedBy: actor.displayName }, + { ...stuck, id: `eval-skip-${++this.#seq}`, outcome: 'skipped', requestedAt: now, finishedAt: now, runIds: [], skippedFor: [], failureCode: null, error: null, abandonedBecause: null, skipReason: reason, skippedBy: actor.displayName, unreadable: null }, ...(this.#fx.evaluations[def.name] ?? []) ]; this.#runtime(scope, def.name).history.unshift(this.#stateEvent('event_skipped', reason, eventId)); diff --git a/ui/src/lib/api/mock/operate.ts b/ui/src/lib/api/mock/operate.ts index 39e421b1c0..ed62a0bc04 100644 --- a/ui/src/lib/api/mock/operate.ts +++ b/ui/src/lib/api/mock/operate.ts @@ -24,7 +24,7 @@ import type { } from '../types'; import { CI_ACCOUNT, DEMO_USER, OPS_USER, SCHEDULER, SENSOR_DAEMON } from './principals'; import { BIG_GROUP, bigGroupFile, bigGroupSelect, bigGroupShape } from './big-group'; -import { resolveSelection, writeSetOf } from './operate-graph'; +import { resolveSelection, setJobResolver, writeSetOf } from './operate-graph'; import type { RunEnd, RunRecord, RunScript } from './run-detail'; const MIN = 60_000; @@ -121,6 +121,33 @@ export const JOB_DEFS: JobDef[] = [ ignore_audit_failures=True, owner="data-platform", schedule=schedule(cron="{cron:core_build}", timezone="UTC"), +)` + ) + }, + { + key: 'shop_daily', + kind: 'job', + description: 'Every model of the shop, daily: staging, marts, finance, inventory, fulfillment and reporting', + select: 'path:models', + exclude: [], + members: [], + overlap: 'skip', + onFailure: null, + pools: {}, + priority: 0, + sourceFile: 'orchestration/jobs.py', + settings: {}, + targets: null, + owner: 'data-platform', + criticalNodes: [], + declaration: decl( + 'orchestration/jobs.py', + 40, + `shop_daily = job( + "shop_daily", + description="Every model of the shop, daily", + select="path:models", + owner="data-platform", )` ) }, @@ -376,6 +403,8 @@ JOB_DEFS.push( /** Waits a group declares instead of those its members' lineage gives: the big group's whole upstreams. */ export const DECLARED_WAITS: Record> = { [BIG_GROUP]: BIG.waits }; +setJobResolver(jobNodes); + export function jobDef(key: string | null): JobDef | undefined { return key ? JOB_DEFS.find((j) => j.key === key) : undefined; } @@ -980,6 +1009,33 @@ export function createOperateFixtures(now: number): OperateFixtures { nightlyStages ); + // ---- prototype runs (CHI-1591): a failed, a running, a group and a successful run ---- + + record({ + id: 'run-pf31', origin: 'manual', job: 'shop_daily', by: DEMO_USER, queuedAgo: 14.2, startedAgo: 14, durationMin: 3.2, + fail: ['fct_order_margin', 'fct_refunds', 'score_customers_v2'], warn: ['stg_inventory', 'fct_shipments', 'fct_payment_daily', 'fct_order_lines'], + errors: { fct_order_margin: 'Division by zero in margin_pct', fct_refunds: 'Check unique(order_id) failed: 14 duplicate rows', score_customers_v2: "KeyError: 'customer_segment'" } + }); + record({ id: 'run-pr02', origin: 'manual', job: 'shop_daily', by: DEMO_USER, queuedAgo: 0.6, startedAgo: 0.5, durationMin: 20, running: true, warn: ['stg_inventory'] }); + record({ id: 'run-ps07', origin: 'schedule', job: 'shop_daily', by: SCHEDULER, queuedAgo: 1442, startedAgo: 1441.8, durationMin: 2.6 }); + groupRun( + { id: 'run-pg40', origin: 'manual', job: 'nightly_all', by: DEMO_USER, queuedAgo: 42, startedAgo: 41.8 }, + { + load_sources: { durationMin: 2 }, + core_build: { durationMin: 4, fail: ['daily_revenue'], errors: { daily_revenue: 'Division by zero in revenue_per_order' } }, + activity_microbatch: { durationMin: 3 }, + reporting_exports: { durationMin: 1 } + }, + nightlyStages + ); + { + // The last member never starts: the group stops it after core_build failed. + const last = records.find((r) => r.run.id === 'run-pg40-rep')!; + const parentEnd = Date.parse(records.find((r) => r.run.id === 'run-pg40-act')!.run.endedAt!); + Object.assign(last.run, { status: 'skipped', startedAt: null, launchedAt: null, endedAt: new Date(parentEnd).toISOString(), statusReason: 'Not started: core_build failed earlier in this group run' }); + last.script.end = 'never_started'; + } + // ---- generated schedule history ---- const fixtureTicks = new Map>(); @@ -1124,6 +1180,7 @@ export function createOperateFixtures(now: number): OperateFixtures { error: null, abandonedBecause: phase === 'abandoned' ? 'superseded' : null, skippedBy: null, + unreadable: null, definitionFingerprint: fingerprint(name), ...extra }); diff --git a/ui/src/lib/api/mock/platform.ts b/ui/src/lib/api/mock/platform.ts index 12bfd1b05f..309f5d169c 100644 --- a/ui/src/lib/api/mock/platform.ts +++ b/ui/src/lib/api/mock/platform.ts @@ -20,6 +20,10 @@ import type { ConnectionTest, EffectiveAccess, IssuedToken, + KeyRotation, + NewServiceAccount, + ServiceAccount, + ServiceAccountKey, JanitorEvent, Location, LocationDetail, @@ -96,6 +100,7 @@ import { } from './access'; import { LOCATION_MARKETING, LOCATION_SHOP, LOCATION_SHOP_DEV, LOCATION_SHOP_STAGING, ROLE_CAPABILITIES, SHOP_LOCATIONS } from './fixtures'; import { poolCapWarnings, triggerId } from './operate'; +import { newServiceKey, serviceAccountAudit, serviceAccountFixtures } from './service-accounts'; import { ALEX, CI_ACCOUNT, DEMO_USER, JORDAN, OPS_USER, REPORTING, RILEY, SAM, SYSTEM, MORGAN } from './principals'; const MIN = 60_000; @@ -109,6 +114,8 @@ export type MockPlatformContext = { /** How people sign in; only password sign-in can add people. */ authMode: AuthMode; user: Principal; + /** `none` starts with no service accounts (`?serviceaccounts=none`). */ + serviceAccounts: 'default' | 'none'; locations: Location[]; changes: LocalChangeBus; platformEvents: () => PlatformEvent[]; @@ -611,9 +618,13 @@ export class MockPlatformApi implements PlatformApi { readonly #data: ReturnType; readonly #connectionTests = new Map(); + readonly #serviceAccounts: ServiceAccount[]; + constructor(ctx: MockPlatformContext) { this.#ctx = ctx; this.#data = createPlatformFixtures(ctx.now, ctx.role); + this.#serviceAccounts = serviceAccountFixtures(ctx.now, ctx.serviceAccounts); + if (ctx.serviceAccounts === 'default') this.#data.auditEntries.push(...serviceAccountAudit(ctx.now)); } /** Records an audited read of check evidence (`view.evidence`). */ @@ -867,7 +878,7 @@ export class MockPlatformApi implements PlatformApi { ...this.#withCounts(role), baseGrants: baseGrantsOf(role), selectors: selectorMatches(role), - assignments: this.#data.assignments.filter((a) => a.role === role.name), + assignments: this.#allAssignments().filter((a) => a.role === role.name), definition: definitionText(role) }; return this.#ctx.reply(structuredClone(detail)); @@ -875,7 +886,17 @@ export class MockPlatformApi implements PlatformApi { async listRoleAssignments(): Promise { this.#require('role.assign'); - return this.#ctx.reply(structuredClone(this.#data.assignments)); + return this.#ctx.reply(structuredClone(this.#allAssignments())); + } + + /** People's assignments and each service account's one role everywhere, as the server lists them. */ + #allAssignments(): RoleAssignment[] { + const services: RoleAssignment[] = this.#serviceAccounts.flatMap((a) => + a.role + ? [{ id: `sa-role-${a.name}`, principal: { kind: 'service', name: a.name, displayName: a.name }, role: a.role, scope: { locationId: null }, source: 'manual', ssoGroup: null, definedIn: null, assignedBy: null, assignedAt: a.createdAt, stale: false }] + : [] + ); + return [...this.#data.assignments, ...services]; } async createRoleAssignment(request: RoleAssignmentRequest): Promise { @@ -949,6 +970,87 @@ export class MockPlatformApi implements PlatformApi { } + // ---- service accounts ---- + + async listServiceAccounts(): Promise { + if (!this.#can('user.manage') && !this.#can('role.assign')) throw new ApiError('Missing permission: user.manage or role.assign', 403); + const now = new Date().toISOString(); + for (const account of this.#serviceAccounts) account.keys = account.keys.filter((k) => !k.expiresAt || k.expiresAt > now); + return this.#ctx.reply(structuredClone(this.#serviceAccounts)); + } + + async createServiceAccount(request: NewServiceAccount): Promise> { + this.#require('user.manage'); + this.#require('role.assign'); + const name = request.name.trim(); + if (!/^[a-z][a-z0-9_-]{1,62}$/.test(name)) throw new ApiError('A name is 2 to 63 lowercase letters, digits, - or _, starting with a letter', 400); + if (this.#serviceAccounts.some((a) => a.name === name) || this.#data.accounts.some((a) => a.name === name)) throw new ApiError(`${name} is already taken by a person or service account`, 400); + const issued = newServiceKey(); + const at = new Date().toISOString(); + const account: ServiceAccount = { + kind: 'service', + name, + displayName: name, + description: request.description?.trim() || null, + role: request.role, + createdAt: at, + createdBy: this.#ctx.user.name, + lastUsedAt: null, + disabled: false, + keys: [{ id: `sak-${randomHex(6)}`, prefix: issued.prefix, createdAt: at, createdBy: this.#ctx.user.name, lastUsedAt: null, expiresAt: null, origin: 'issued' }] + }; + this.#serviceAccounts.push(account); + this.#audit('service_account.created', { locationId: null, subject: name }, `Added service account ${name} as ${request.role}`, null, issued.prefix); + return this.#ctx.reply({ token: structuredClone(account), secret: issued.secret }); + } + + async rotateServiceAccountKey(name: string, rotation: KeyRotation): Promise> { + this.#require('user.manage'); + const account = this.#serviceAccount(name); + const [current] = account.keys; + const issued = newServiceKey(); + const at = new Date(); + const kept: ServiceAccountKey[] = current && rotation.overlapMinutes ? [{ ...current, expiresAt: new Date(at.getTime() + rotation.overlapMinutes * 60_000).toISOString() }] : []; + account.keys = [{ id: `sak-${randomHex(6)}`, prefix: issued.prefix, createdAt: at.toISOString(), createdBy: this.#ctx.user.name, lastUsedAt: null, expiresAt: null, origin: 'issued' }, ...kept]; + const overlap = rotation.overlapMinutes ? `; ${current?.prefix}… works for ${rotation.overlapMinutes} more minutes` : '; the old key stopped at once'; + this.#audit('service_account.key_rotated', { locationId: null, subject: name }, `Rotated ${name}'s key${overlap}`, current?.prefix ?? null, issued.prefix); + return this.#ctx.reply({ token: structuredClone(account), secret: issued.secret }); + } + + async revokeServiceAccountKey(name: string, keyId: string): Promise { + this.#require('user.manage'); + const account = this.#serviceAccount(name); + const key = account.keys.find((k) => k.id === keyId); + if (!key) throw new ApiError(`${name} has no working key ${keyId}`, 404); + account.keys = account.keys.filter((k) => k.id !== keyId); + this.#audit('service_account.key_revoked', { locationId: null, subject: name }, `Stopped ${name}'s key ${key.prefix}…`, key.prefix, null); + return this.#ctx.reply(structuredClone(account)); + } + + async setServiceAccountDisabled(name: string, disabled: boolean): Promise { + this.#require('user.manage'); + const account = this.#serviceAccount(name); + if (account.disabled === disabled) throw new ApiError(`${name} is already ${disabled ? 'disabled' : 'enabled'}`, 409); + account.disabled = disabled; + this.#audit(disabled ? 'service_account.disabled' : 'service_account.enabled', { locationId: null, subject: name }, `${disabled ? 'Disabled' : 'Enabled'} service account ${name}`, disabled ? 'active' : 'disabled', disabled ? 'disabled' : 'active'); + return this.#ctx.reply(structuredClone(account)); + } + + async setServiceAccountRole(name: string, role: BuiltInRole): Promise { + this.#require('role.assign'); + const account = this.#serviceAccount(name); + const before = account.role; + account.role = role; + this.#audit('service_account.role_changed', { locationId: null, subject: name }, `Gave ${name} ${role} everywhere`, before, role); + return this.#ctx.reply(structuredClone(account)); + } + + #serviceAccount(name: string): ServiceAccount { + const account = this.#serviceAccounts.find((a) => a.name === name); + if (!account) throw new ApiError(`Unknown service account ${name}`, 404); + return account; + } + // ---- audit and access ---- async listAuditEntries(query: AuditQuery = {}): Promise { diff --git a/ui/src/lib/api/mock/run-detail.ts b/ui/src/lib/api/mock/run-detail.ts index f5800ea322..5b84c35dae 100644 --- a/ui/src/lib/api/mock/run-detail.ts +++ b/ui/src/lib/api/mock/run-detail.ts @@ -3,6 +3,7 @@ // facts. Pure: the same record and clock always give the same detail. import type { + RunEventCheck, CancelProgress, LaunchVerb, NodeCounts, @@ -19,6 +20,25 @@ import type { SkippedBecauseOf } from '../types'; import { ancestors, snapshotNode, sortTopologically } from './operate-graph'; +import { NODE_SPECS } from './build-fixtures'; +import { BIG_NODE, OUTPUT_SOURCES, V2_NODE, V2_TRACEBACK, bigAvailable } from './big-output'; + +/** The prototype runs (CHI-1591), run by a local worker process and printing sqb's own lines. */ +const PROTO = /^run-p(f31|r02|s07|g40)/; +/** Rows a prototype node writes per second while it builds, for its progress. */ +const protoRate = (key: string) => 37 + (hash(key) % 400); +/** + * Honest progress (CHI-1591): only loaders and microbatch models know their rows while they run; a + * warehouse statement reports none until it finishes, so other nodes show elapsed time only. + */ +const reportsRowsWhileRunning = (key: string) => snapshotNode(key)?.kind === 'loader' || !!NODE_SPECS[key]?.microbatch; +/** Rows a finished node reports: added rows for incrementals and loaders, the table's count from metadata after a rebuild, none for views and tasks. */ +const finishedRows = (key: string, ms: number): number | null => { + const kind = snapshotNode(key)?.kind; + if (kind === 'view' || kind === 'asset') return null; + if (kind === 'incremental' || kind === 'loader') return Math.round((ms / 1000) * protoRate(key)); + return 800 + (hash(`${key}/rows`) % 60_000); +}; /** `crashed`: the worker stopped before building anything, as when its plan is refused; `crashError` says why. */ export type RunEnd = 'complete' | 'cancelled' | 'presumed_failed' | 'never_started' | 'crashed'; @@ -155,20 +175,23 @@ export function computeNodes(record: RunRecord, siblings: RunRecord[], now: numb const status: RunNodeStatus = fails ? 'failed' : script.warn.includes(key) ? 'warn' : 'success'; if (fails) failed.set(key, { nodeKey: key, runId: run.id, jobKey: run.jobKey, at: e }); const message = fails ? (script.errors[key] ?? 'Statement failed in the warehouse') : null; + const python = fails && key === V2_NODE; return { ...base(key, status), startedAt: iso(s), endedAt: iso(e), - rowsAffected: fails || snapshotNode(key)?.kind === 'view' ? null : 120 + (hash(key + run.id) % 48000), - errorCode: fails ? 'E2103' : null, + rowsAffected: (fails && !CHECK_FAILS.has(key)) || snapshotNode(key)?.kind === 'view' ? null : PROTO.test(run.id) ? finishedRows(key, e - s) : 120 + (hash(key + run.id) % 48000), + // As sqb reports them: R006 for a failed check, no code for a Python exception, the warehouse's own otherwise. + errorCode: fails ? (CHECK_FAILS.has(key) ? 'R006' : python ? null : 'E2103') : null, errorMessage: message, - ...(fails ? failureDetail(key, run, message ?? '') : {}) + ...(fails ? (CHECK_FAILS.has(key) ? checkFailureDetail(key) : python ? pythonFailureDetail() : failureDetail(key, run, message ?? '')) : {}) }; }; if (terminal && script.end === 'complete') return finish(); if (e <= clock) return finish(); if (s <= clock) { - if (!terminal) return { ...base(key, 'running'), startedAt: iso(s) }; + // A prototype run reports rows so far while a node builds, for the timeline bar and the drawer. + if (!terminal) return { ...base(key, 'running'), startedAt: iso(s), rowsAffected: PROTO.test(run.id) && reportsRowsWhileRunning(key) ? Math.round(((clock - s) / 1000) * protoRate(key)) : null }; if (script.end === 'presumed_failed') return { ...base(key, 'failed'), @@ -185,6 +208,62 @@ export function computeNodes(record: RunRecord, siblings: RunRecord[], now: numb }); } +// ---- several checks on one node (CHI-1591) ---- + +/** Checks that fail or warn on a node that warns or fails by a check: severity and the rows they found. */ +const CHECK_PROFILE: Record> = { + stg_inventory: { 'not_null(product_id)': ['warn', 3] }, + fct_shipments: { 'not_null(shipment_id)': ['warn', 4] }, + fct_payment_daily: { 'not_null(payment_id)': ['warn', 2] }, + fct_order_lines: { 'not_null(payment_id)': ['warn', 2], 'unique(order_id)': ['warn', 6] }, + fct_refunds: { 'unique(order_id)': ['error', 14], 'not_null(payment_id)': ['warn', 2], 'accepted_values(status)': ['warn', 5], 'not_null(reason)': ['warn', 9] } +}; +/** Nodes that built but failed on an error-severity check. */ +const CHECK_FAILS = new Set(['fct_refunds']); + +export const auditStatementId = (run: Run, nodeKey: string, i: number) => `${statementIdOf(run, nodeKey)}-audit-${i}`; + +/** A node's checks, as `name(column)`, in declaration order. */ +export function auditsOf(key: string): string[] { + return (NODE_SPECS[key]?.columns ?? []).flatMap((c) => (c.audits ?? []).map((a) => `${a}(${c.name})`)); +} + +/** A check's query as it ran, compiled. */ +export function auditSql(nodeKey: string, statementId: string, target: string): string { + const i = Number(statementId.split('-audit-')[1] ?? 0); + const audit = auditsOf(nodeKey)[i] ?? 'not_null(id)'; + const [, name, col] = audit.match(/^(\w+)\((\w+)\)$/) ?? []; + const rel = `${target === 'dev' ? 'dev_demo' : 'analytics'}.${nodeKey}`; + if (name === 'unique') return `select ${col}, count(*) as n\nfrom ${rel}\nwhere ${col} is not null\ngroup by ${col}\nhaving count(*) > 1`; + if (name === 'accepted_values') return `select ${col}, count(*) as n\nfrom ${rel}\nwhere ${col} not in ('paid', 'pending', 'refunded', 'void')\ngroup by ${col}`; + return `select *\nfrom ${rel}\nwhere ${col} is null`; +} + +/** The failing rows a check found, as a small sample (the server keeps the first 100). */ +export function auditSample(nodeKey: string, statementId: string, count: number): { columns: string[]; rows: (string | number | null)[][]; total: number } { + const i = Number(statementId.split('-audit-')[1] ?? 0); + const audit = auditsOf(nodeKey)[i] ?? 'not_null(id)'; + const [, name, col] = audit.match(/^(\w+)\((\w+)\)$/) ?? []; + const n = Math.min(count, 8); + const id = (j: number) => 10_400 + ((hash(`${statementId}${j}`) % 9_000) | 0); + if (name === 'unique') return { columns: [col, 'n'], rows: Array.from({ length: n }, (_, j) => [id(j), 2 + (j % 2)]), total: count }; + if (name === 'accepted_values') return { columns: [col, 'n'], rows: ['paid ', 'PAID', 'refund', 'unknown', 'n/a'].slice(0, n).map((v, j) => [v, 1 + j]), total: count }; + return { columns: ['order_id', col, 'created_at'], rows: Array.from({ length: n }, (_, j) => [id(j), null, `2026-11-${String(10 + j).padStart(2, '0')} 0${j}:14:0${j}`]), total: count }; +} + +/** A Python node's exception: where it was raised in the node's own code, and the whole traceback. */ +function pythonFailureDetail(): Pick { + return { errorLocation: { file: 'models/ml/score_customers_v2.py', line: 26 }, errorDetail: V2_TRACEBACK.join('\n') }; +} + +function checkFailureDetail(key: string): Pick { + const file = (snapshotNode(key)?.path ?? `models/${key}.sql`).replace(/\.sql$/, '.yml'); + return { + errorLocation: { file, line: 12 }, + errorDetail: ['check unique(order_id) failed: 14 duplicate rows (severity error)', ` --> ${file}:12`, '', 'The table was built, then its error-severity check failed, so the node failed and its downstream was skipped.'].join('\n') + }; +} + /** Mock failure location and full text: the model file, and a line inside its main statement. */ function failureDetail(key: string, run: Run, message: string): Pick { const file = snapshotNode(key)?.path ?? `models/${key}.sql`; @@ -216,12 +295,15 @@ export function queryIdOf(statementId: string): string { } export function countNodes(nodes: RunNode[]): NodeCounts { - const c: NodeCounts = { success: 0, warn: 0, failed: 0, skipped: 0, running: 0, pending: 0 }; + const c: NodeCounts = { success: 0, warn: 0, failed: 0, skipped: 0, running: 0, pending: 0, notRun: 0 }; for (const n of nodes) { if (n.status === 'success') c.success++; else if (n.status === 'warn') c.warn++; else if (n.status === 'failed') c.failed++; - else if (n.status === 'skipped' || n.status === 'cancelled' || n.status === 'not_run') c.skipped++; + else if (n.status === 'skipped' || n.status === 'cancelled' || n.status === 'not_run') { + c.skipped++; + if (n.status !== 'skipped') c.notRun!++; + } else if (n.status === 'running') c.running++; else c.pending++; } @@ -259,6 +341,7 @@ export function statusReason(status: RunStatus, nodes: RunNode[]): string | null // ---- Recall events, statements and output ---- const LEVEL: Record = { + node_log: 'info', invocation_started: 'info', invocation_completed: 'info', invocation_failed: 'error', @@ -360,7 +443,8 @@ export function execution(record: RunRecord, nodes: RunNode[], now?: number): Ru drafts.push({ producer: 'scheduler', type, occurredAt: typeof at === 'number' ? iso(at) : at, invocationId: null, nodeKey: null, statementId: null, attempt: null, message }); const ev = (type: Draft['type'], at: number, nodeKey: string | null, message: string, statementId: string | null = null) => drafts.push({ type, occurredAt: iso(at), invocationId: inv, nodeKey, statementId, attempt: nodeKey ? 1 : null, message }); - const out = (stream: RunOutputLine['stream'], at: number, text: string, error = false) => inv && output.push({ invocationId: inv, stream, at: iso(at), text, error }); + const out = (stream: RunOutputLine['stream'], at: number, text: string, error = false, nodeKey: string | null = null, omitted?: number) => + inv && output.push({ invocationId: inv, stream, at: iso(at), text, error, ...(nodeKey ? { nodeKey } : {}), ...(omitted ? { omitted } : {}) }); const queued = Date.parse(run.queuedAt); fact('requested', queued - 200, `Requested by ${run.requestedBy.displayName}${run.triggerName ? ` via ${run.triggerName}` : ''}`); @@ -368,11 +452,13 @@ export function execution(record: RunRecord, nodes: RunNode[], now?: number): Ru if (run.launchedAt) { const launched = Date.parse(run.launchedAt); fact('claimed', launched - 300, script.nodes.length ? `Claimed ${script.nodes.length} write-set nodes${Object.keys(script.pools).length ? ` and slots in pool ${Object.keys(script.pools).join(', ')}` : ''}` : 'Claimed'); - fact('launched', launched, script.nodes.length ? `Container started from image ${script.imageId.slice(0, 19)}` : `Started ${run.childRunCount} child runs in order`); + fact('launched', launched, PROTO.test(run.id) ? (script.nodes.length ? 'Worker started (local process)' : `Started ${run.childRunCount} member job runs in order`) : script.nodes.length ? `Container started from image ${script.imageId.slice(0, 19)}` : `Started ${run.childRunCount} child runs in order`); } if (script.cancel) fact('cancel_requested', script.cancel.requestedAt, `Cancel requested by ${script.cancel.requestedBy.displayName}`); - if (inv && run.startedAt) { + if (inv && run.startedAt && PROTO.test(run.id)) { + protoExecution(record, nodes, now ?? Date.now(), { ev, out, statements, inv }); + } else if (inv && run.startedAt) { const start = Date.parse(run.startedAt); ev('invocation_started', start, null, commandOf(record)); out('stdout', start, `$ ${commandOf(record)}`); @@ -462,16 +548,235 @@ export function execution(record: RunRecord, nodes: RunNode[], now?: number): Ru producer: d.producer ?? 'sqb', type: d.type, occurredAt: d.occurredAt, - level: LEVEL[d.type], + level: + d.type === 'audit_completed' && /\(severity error\)$/.test(d.message) + ? 'error' + : (d.type === 'audit_completed' && /\(severity warn\)$/.test(d.message)) || (d.type === 'node_log' && d.message.startsWith('[warning] ')) + ? 'warn' + : LEVEL[d.type], invocationId: d.invocationId, nodeKey: d.nodeKey, statementId: d.statementId, attempt: d.attempt, - message: d.message + message: d.message, + ...(d.type === 'audit_completed' ? { check: mockCheck(d.message) } : {}) })); return { events, statements, output: output.sort((a, b) => a.at.localeCompare(b.at)) }; } +type Emit = { + ev: (type: RunEvent['type'], at: number, nodeKey: string | null, message: string, statementId?: string | null) => void; + out: (stream: RunOutputLine['stream'], at: number, text: string, error?: boolean, nodeKey?: string | null, omitted?: number) => void; + statements: RunStatement[]; + inv: string; +}; + +/** What a prototype Python node prints while it runs: its own stdout, and a warning with a traceback on stderr. */ +function pythonOutput(key: string, s: number, e: number | null, now: number, out: Emit['out']) { + const until = e ?? now; + const at = (ms: number) => s + ms; + const line = (ms: number, stream: RunOutputLine['stream'], text: string) => at(ms) < until && out(stream, at(ms), text, false, key); + if (key === 'raw_events') { + line(400, 'stdout', 'Fetching events since 2026-11-20T09:00:00Z'); + for (let page = 1, t = 6_000; t < (e ?? now) - s; page++, t += 9_000) { + line(t, 'stdout', `Page ${page}: ${(11_000 + (hash(`${key}${page}`) % 2_000)).toLocaleString('en-GB')} events`); + if (page === 3) + line( + t + 2_500, + 'stderr', + [ + 'WARNING shop.events: page 4 failed, retrying in 5s', + 'Traceback (most recent call last):', + ' File "/app/models/ingest/raw_events.py", line 18, in raw_events', + ' rows = fetch_page(since=ctx.current_cursor_value, page=page)', + ' File "/app/shop/events_api.py", line 41, in fetch_page', + ' resp.raise_for_status()', + 'requests.exceptions.HTTPError: 503 Server Error: Service Unavailable for url: https://events.example.com/v1/events?page=4' + ].join('\n') + ); + } + } + const src = OUTPUT_SOURCES[key]; + if (src) { + // The live view is capped (CHI-1597): a marker for what came before, then the latest lines; the rest is in the viewer. + const n = { nodeKey: key, startedAt: new Date(s).toISOString(), status: e == null ? 'running' : 'success' } as RunNode; + const big = bigAvailable(n, until); + if (!big) return; + // Capped only past about 1,000 lines: then the last 40, and the rest in the viewer. + const LIVE = big.available > 1_000 ? 40 : big.available; + const first = Math.max(1, big.available - LIVE + 1); + if (first > 1) out('stdout', until - 1_000, `${(first - 1).toLocaleString('en-GB')} earlier lines`, false, key, first - 1); + for (let i = first; i <= big.available; i++) { + const l = src.line(i); + out(l.stream, until - 1_000 + (i - first) * 20, l.text, false, key); + } + return; + } + if (key === 'score_customers') { + line(500, 'stdout', 'Loaded 4,812 customers'); + line( + 1_400, + 'stderr', + [ + '/app/models/ml/score_customers.py:11: FutureWarning: DataFrame.fillna with \'method\' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead.', + ' features = features.fillna(method="ffill")' + ].join('\n') + ); + if (e != null) line(e - s - 300, 'stdout', 'Scored 4,812 customers'); + } +} + +/** The heartbeat's backoff: 30 s, then 1 min, 2 min, and every 5 min after that. */ +function heartbeatTimes(start: number, until: number): number[] { + const gaps = [30_000, 60_000, 120_000]; + const out: number[] = []; + for (let t = start, i = 0; ; i++) { + t += gaps[i] ?? 300_000; + if (t >= until) return out; + out.push(t); + } +} + +/** + * A prototype run's events and what sqb printed. Each check is its own event (the page folds them into + * their node's line); sqb prints a progress line for a building node every 30 seconds, and every line + * it prints for a node carries that node. + */ +function protoExecution(record: RunRecord, nodes: RunNode[], now: number, { ev, out, statements, inv }: Emit) { + const { run, script } = record; + const start = Date.parse(run.startedAt!); + const secs = (ms: number) => `${(ms / 1000).toFixed(1)}s`; + const rows = (n: number) => n.toLocaleString('en-GB'); + ev('invocation_started', start, null, commandOf(record)); + // sqb prints its progress on stdout, and warnings and errors on stderr. + out('stdout', start + 120, `sqb ${commandOf(record).replace(/^sqb /, '')}`); + out('stdout', start + 450, `✓ Project compiled ${script.nodes.length} models 0.4s`); + out('stdout', start + 900, '✓ Warehouse connected snowflake 0.1s'); + out('stdout', start + 1100, `Building ${script.nodes.length} nodes, 4 at a time`); + const audits = auditsOf; + for (const n of nodes) { + const k = snapshotNode(n.nodeKey)?.kind ?? 'table'; + const key = n.nodeKey; + if (n.status === 'skipped' && n.endedAt) { + const why = n.skippedBecauseOf; + // Every skip names its cause, chain included: the skipped parent it waited on, and the failure behind it. + const via = why ? nodes.find((p) => p.status === 'skipped' && p.skippedBecauseOf?.nodeKey === why.nodeKey && (snapshotNode(key)?.upstream ?? []).includes(p.nodeKey)) : undefined; + const across = why && why.runId !== run.id ? ` in ${why.jobKey ?? why.runId}` : ''; + const cause = !why ? 'an upstream node did not run' : via ? `${via.nodeKey} was skipped (after ${why.nodeKey} failed${across})` : `${why.nodeKey} failed${across}`; + ev('resource_attempt_skipped', Date.parse(n.endedAt), key, `Skipped: ${cause}`); + out('stdout', Date.parse(n.endedAt), ` – ${key} skipped: ${cause}`, false, key); + continue; + } + if (!n.startedAt) continue; + const s = Date.parse(n.startedAt); + const e = n.endedAt ? Date.parse(n.endedAt) : null; + ev('resource_attempt_started', s, key, `Started ${k} ${key}`); + out('stdout', s, ` ▸ ${key} ${k}`, false, key); + pythonOutput(key, s, e, now, out); + if (key === BIG_NODE) { + // Its ctx.log lines: few and deliberate, kept as events (CHI-1597). + ev('node_log', s + 1_500, key, 'Running notebook churn_features.ipynb (48 cells)'); + if ((e ?? now) - s > 3_000) ev('node_log', s + ((e ?? now) - s) / 2, key, '[warning] cell 18 retried after worker loss'); + if (e != null) ev('node_log', e - 200, key, 'Notebook finished: 48 cells, 211,604 rows written'); + } + const kind = STATEMENT_KIND[k]; + if (kind) { + // The node's warehouse statement, with its query ID, for the Statements tab, the cost and the drawer. + const statementId = statementIdOf(run, key); + const stEnd = e != null ? e - 120 : null; + // A node failed by a check built fine: its build query completed. + const failed = n.status === 'failed' && !CHECK_FAILS.has(key); + statements.push({ + id: statementId, + runId: run.id, + invocationId: inv, + sequence: statements.length + 1, + nodeKey: key, + kind, + status: n.status === 'running' ? 'running' : failed ? 'failed' : 'completed', + startedAt: iso(s + 60), + endedAt: stEnd == null ? null : iso(stEnd), + rowsAffected: n.status === 'running' ? null : n.rowsAffected, + rowsSoFar: n.status === 'running' && reportsRowsWhileRunning(key) ? n.rowsAffected : null, + queryId: queryIdOf(statementId), + sqlRecorded: true, + error: failed ? (n.errorDetail ?? n.errorMessage) : null + }); + ev('statement_submitted', s + 40, key, `${kind} submitted`, statementId); + ev('statement_started', s + 60, key, `${kind} running`, statementId); + if (stEnd != null) { + if (failed) ev('statement_failed', stEnd, key, n.errorMessage ?? 'Statement failed', statementId); + else ev('statement_completed', stEnd, key, n.rowsAffected != null ? `${rows(n.rowsAffected)} rows` : 'Completed', statementId); + } + } + if (e == null) continue; + const took = secs(e - s); + const checkFailed = CHECK_FAILS.has(key) && n.status === 'failed'; + if (n.status === 'failed' && !checkFailed) { + ev('resource_attempt_failed', e, key, `${n.errorCode}: ${n.errorMessage}`); + out('stderr', e, ` ✗ ${key} ${k} ${took} ${n.errorMessage}`, true, key); + continue; + } + const added = k === 'incremental' && n.rowsAffected != null ? ` +${rows(n.rowsAffected)} rows` : n.rowsAffected != null ? ` ${rows(n.rowsAffected)} rows` : ''; + if (!checkFailed) ev('resource_attempt_completed', e, key, `${n.status === 'warn' ? 'Completed with warnings' : 'Completed'} in ${took}${added ? ` ·${added.replace(/^ +/, ' ')}` : ''}`); + out('stdout', e, ` ✓ ${key} ${k} ${took}${added}`, false, key); + // Each check is its own query: an event with its statement, so its SQL, query ID and failing rows can be read. + const profile = n.status === 'warn' || checkFailed ? (CHECK_PROFILE[key] ?? null) : null; + audits(key).forEach((audit, i) => { + const problem = profile ? profile[audit] : n.status === 'warn' && i === 0 ? (['warn', 2 + (hash(key) % 5)] as const) : undefined; + const at = e + 40 + i * 120; + const statementId = auditStatementId(run, key, i); + statements.push({ + id: statementId, + runId: run.id, + invocationId: inv, + sequence: statements.length + 1, + nodeKey: key, + kind: 'audit', + status: 'completed', + startedAt: iso(at - 90 - (hash(statementId) % 300)), + endedAt: iso(at), + rowsAffected: problem ? problem[1] : 0, + rowsSoFar: null, + queryId: queryIdOf(statementId), + sqlRecorded: true, + error: null + }); + const noun = audit.startsWith('unique') ? 'duplicate rows' : 'failing rows'; + ev('audit_completed', at, key, problem ? `${audit}: ${problem[1]} ${noun} (severity ${problem[0]})` : `${audit} passed`, statementId); + if (problem) out('stderr', at, ` ${problem[0] === 'error' ? '✗' : '!'} ${key} check ${audit}: ${problem[1]} ${noun} (${problem[0]})`, problem[0] === 'error', key); + }); + if (checkFailed) { + const at = e + 60 + audits(key).length * 120; + ev('resource_attempt_failed', at, key, `check_failed: ${n.errorMessage}`); + out('stderr', at, ` ✗ ${key} ${k} ${took} ${n.errorMessage}`, true, key); + } + } + // One combined heartbeat line for whatever is still running, backing off: 30 s, 1 min, 2 min, then every 5 min. + const firstStart = Math.min(...nodes.map((n) => (n.startedAt ? Date.parse(n.startedAt) : Infinity))); + if (Number.isFinite(firstStart)) { + const until = run.endedAt ? Date.parse(run.endedAt) : now; + for (const t of heartbeatTimes(firstStart, until)) { + const busy = nodes.filter((n) => n.startedAt && Date.parse(n.startedAt) <= t && (!n.endedAt || Date.parse(n.endedAt) > t)); + if (!busy.length) continue; + const span = (ms: number) => (ms >= 60_000 ? `${Math.floor(ms / 60_000)}m${String(Math.floor((ms % 60_000) / 1000)).padStart(2, '0')}s` : `${Math.floor(ms / 1000)}s`); + const parts = busy.map((n) => { + const ms = t - Date.parse(n.startedAt!); + return `${n.nodeKey} ${span(ms)}${reportsRowsWhileRunning(n.nodeKey) ? ` (${rows(Math.round((ms / 1000) * protoRate(n.nodeKey)))} rows)` : ''}`; + }); + out('stdout', t, `… still running (${busy.length}) ${parts.join(' · ')}`); + } + } + if (run.endedAt) { + const end = Date.parse(run.endedAt) - 400; + const c = countNodes(nodes); + const summary = `${c.success + c.warn} built · ${c.failed} failed · ${c.skipped} skipped`; + const ok = c.failed === 0; + ev(ok ? 'invocation_completed' : 'invocation_failed', end, null, `${summary} · ${secs(end - start)}`); + out(ok ? 'stdout' : 'stderr', end, `${ok ? '✓ Completed' : '✗ Completed with errors'} ${summary} ${secs(end - start)}`); + } +} + export function liveness(record: RunRecord, now: number): RunLiveness | null { const { run, script } = record; if (!script.nodes.length || !run.launchedAt) return null; @@ -493,3 +798,10 @@ export function liveness(record: RunRecord, now: number): RunLiveness | null { if (isTerminal(run.status)) return { ...base, state: 'exited', lastHeartbeatAt: iso(heartbeat), exitCode }; return { ...base, state: 'healthy', lastHeartbeatAt: iso(heartbeat), exitCode: null }; } + +/** The check an `audit_completed` message of this mock describes, as the server reports it. */ +function mockCheck(message: string): RunEventCheck { + const m = message.match(/^(.*?): ([\d,]+) .*? \(severity (\w+)\)$/); + if (m) return { name: m[1], outcome: m[3] === 'error' ? 'failed' : 'warned', rows: Number(m[2].replace(/,/g, '')), bindingKey: null, resultId: null }; + return { name: message.replace(/ passed$/, ''), outcome: 'passed', rows: null, bindingKey: null, resultId: null }; +} diff --git a/ui/src/lib/api/mock/service-accounts.ts b/ui/src/lib/api/mock/service-accounts.ts new file mode 100644 index 0000000000..b2f09c05a0 --- /dev/null +++ b/ui/src/lib/api/mock/service-accounts.ts @@ -0,0 +1,99 @@ +import type { AuditEntry, Principal, ServiceAccount, ServiceAccountKey } from '../types'; +import { LOCATION_SHOP, LOCATION_SHOP_STAGING } from './fixtures'; +import { ALEX, DEMO_USER } from './principals'; + +const MIN = 60_000; +const DAY = 24 * 60 * MIN; +const KEY_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; +/** Characters of a key after `sqbk_`; its prefix shows the first `PREFIX_CHARS` of them. */ +const KEY_CHARS = 40; +const PREFIX_CHARS = 6; + +/** The deploy script that republishes the waffle-shop project after each release. */ +export const ORDERS_DEPLOY: Principal = { kind: 'service', name: 'orders-deploy', displayName: 'orders-deploy' }; +export const CI_RUNNER: Principal = { kind: 'service', name: 'ci-runner', displayName: 'ci-runner' }; +export const REPORT_EXPORT: Principal = { kind: 'service', name: 'report-export', displayName: 'report-export' }; + +/** A new key: the secret, shown once, and its non-secret prefix. */ +export function newServiceKey(): { secret: string; prefix: string } { + const bytes = new Uint8Array(KEY_CHARS); + crypto.getRandomValues(bytes); + const body = [...bytes].map((b) => KEY_ALPHABET[b % KEY_ALPHABET.length]).join(''); + return { secret: `sqbk_${body}`, prefix: `sqbk_${body.slice(0, PREFIX_CHARS)}` }; +} + +/** + * Three service accounts: `orders-deploy` part-way through a rotation, whose old key still works for + * 50 minutes and was used after the new one was issued; `ci-runner` with a key imported with the CLI; + * and a disabled `report-export`. `none` has none yet. + */ +export function serviceAccountFixtures(now: number, which: 'default' | 'none'): ServiceAccount[] { + if (which === 'none') return []; + const ago = (minutes: number) => new Date(now - minutes * MIN).toISOString(); + const ahead = (minutes: number) => new Date(now + minutes * MIN).toISOString(); + const key = (id: string, prefix: string, createdMinutesAgo: number, usedMinutesAgo: number | null, extra: Partial = {}): ServiceAccountKey => ({ + id, + prefix, + createdAt: ago(createdMinutesAgo), + createdBy: DEMO_USER.name, + lastUsedAt: usedMinutesAgo === null ? null : ago(usedMinutesAgo), + expiresAt: null, + origin: 'issued', + ...extra + }); + return [ + { + ...ORDERS_DEPLOY, + kind: 'service', + description: 'Release pipeline: republishes waffle-shop after each deploy', + role: 'developer', + createdAt: ago((90 * DAY) / MIN), + createdBy: DEMO_USER.name, + lastUsedAt: ago(3), + disabled: false, + keys: [key('sak-4', 'sqbk_Q7m2xT', 10, null), key('sak-3', 'sqbk_b81LkD', (60 * DAY) / MIN, 3, { expiresAt: ahead(50) })] + }, + { + ...CI_RUNNER, + kind: 'service', + description: 'Runs checks_only on every pull request', + role: 'operator', + createdAt: ago((30 * DAY) / MIN), + createdBy: ALEX.name, + lastUsedAt: ago(125), + disabled: false, + keys: [key('sak-2', 'sqbk_Zp0aW9', (30 * DAY) / MIN, 125, { createdBy: ALEX.name, origin: 'imported' })] + }, + { + ...REPORT_EXPORT, + kind: 'service', + description: 'Old nightly export, replaced by the reporting job', + role: 'viewer', + createdAt: ago((200 * DAY) / MIN), + createdBy: DEMO_USER.name, + lastUsedAt: ago((41 * DAY) / MIN), + disabled: true, + keys: [key('sak-1', 'sqbk_m3TfQe', (200 * DAY) / MIN, (41 * DAY) / MIN)] + } + ]; +} + +/** What the service accounts did lately: republishes by the deploy script (one refused), checks by CI, and the rotation now in its overlap. */ +export function serviceAccountAudit(now: number): AuditEntry[] { + const ago = (minutes: number) => new Date(now - minutes * MIN).toISOString(); + let seq = 0; + const entry = (minutesAgo: number, e: Pick & Partial): AuditEntry => { + seq += 1; + return { id: `aud-sa-${seq}`, at: ago(minutesAgo), outcome: 'allowed', grantingRole: null, decisionId: null, evidenceRead: false, before: null, after: null, ip: '10.0.2.14', requestId: `req-sa-${seq}`, ...e }; + }; + return [ + entry(3, { actor: ORDERS_DEPLOY, action: 'snapshot.republished', scope: { locationId: LOCATION_SHOP_STAGING, subject: 'waffle-shop/staging' }, grantingRole: 'developer', summary: 'Republished waffle-shop/staging with the old key sqbk_b81LkD…', before: 'snapshot 412', after: 'snapshot 413' }), + entry(10, { actor: DEMO_USER, action: 'service_account.key_rotated', scope: { locationId: null, subject: 'orders-deploy' }, grantingRole: 'admin', summary: "Rotated orders-deploy's key; sqbk_b81LkD… works for 60 more minutes", before: 'sqbk_b81LkD', after: 'sqbk_Q7m2xT', ip: '10.0.4.17' }), + entry(125, { actor: CI_RUNNER, action: 'job.run', scope: { locationId: LOCATION_SHOP_STAGING, subject: 'checks_only' }, grantingRole: 'operator', summary: 'Launched checks_only', after: 'run-7d21 queued', ip: '10.0.2.8' }), + entry(250, { actor: ORDERS_DEPLOY, action: 'snapshot.republished', scope: { locationId: LOCATION_SHOP, subject: 'waffle-shop/prod' }, grantingRole: 'developer', summary: 'Republished waffle-shop/prod', before: 'snapshot 287', after: 'snapshot 288' }), + entry(252, { actor: ORDERS_DEPLOY, action: 'location.manage', outcome: 'denied', decisionId: 'dec-9s4d1k', scope: { locationId: LOCATION_SHOP, subject: 'waffle-shop' }, summary: 'Denied: developer can’t change a location’s settings', ip: '10.0.2.14' }), + entry(1440 + 30, { actor: ORDERS_DEPLOY, action: 'snapshot.republished', scope: { locationId: LOCATION_SHOP_STAGING, subject: 'waffle-shop/staging' }, grantingRole: 'developer', summary: 'Republished waffle-shop/staging', before: 'snapshot 411', after: 'snapshot 412' }), + entry(41 * 1440, { actor: REPORT_EXPORT, action: 'view', scope: { locationId: LOCATION_SHOP, subject: 'fact_orders' }, grantingRole: 'viewer', summary: 'Read fact_orders for the nightly export' }), + entry(40 * 1440, { actor: DEMO_USER, action: 'service_account.disabled', scope: { locationId: null, subject: 'report-export' }, grantingRole: 'admin', summary: 'Disabled service account report-export', before: 'active', after: 'disabled', ip: '10.0.4.17' }) + ]; +} diff --git a/ui/src/lib/api/platform-client.ts b/ui/src/lib/api/platform-client.ts index 5501e8de63..29d8eb207e 100644 --- a/ui/src/lib/api/platform-client.ts +++ b/ui/src/lib/api/platform-client.ts @@ -4,10 +4,14 @@ import type { AccessOverview, AccessQuery, Account, + BuiltInRole, AuditEntry, AuditQuery, ConnectionTest, IssuedToken, + KeyRotation, + NewServiceAccount, + ServiceAccount, LocationDetail, LocationSummary, LocationToken, @@ -75,6 +79,18 @@ export interface PlatformApi { enableAccount(name: string): Promise; /** Adds a person who signs in with a password, only under password sign-in. `user.manage`, and `role.assign` to give a role. */ createPasswordAccount(request: NewPasswordAccount): Promise; + /** Service accounts with their working keys' prefixes. `user.manage` or `role.assign` */ + listServiceAccounts(): Promise; + /** Adds a service account and issues its first key, returned only this once. `user.manage` and `role.assign` */ + createServiceAccount(request: NewServiceAccount): Promise>; + /** Issues a new key, returned only this once; the old key works on for the overlap, if any. `user.manage` */ + rotateServiceAccountKey(name: string, rotation: KeyRotation): Promise>; + /** Stops one of the account's keys now, such as an old key before its overlap ends. `user.manage` */ + revokeServiceAccountKey(name: string, keyId: string): Promise; + /** Disabling stops every key of the account at once; enabling lets the same keys work again. `user.manage` */ + setServiceAccountDisabled(name: string, disabled: boolean): Promise; + /** Gives the service account a built-in role everywhere. `role.assign` */ + setServiceAccountRole(name: string, role: BuiltInRole): Promise; // ---- roles ---- /** Roles available in a location: built-in, server config and the location's project roles. `role.assign` */ diff --git a/ui/src/lib/api/types.ts b/ui/src/lib/api/types.ts index 1a5ac70223..9996f6ff98 100644 --- a/ui/src/lib/api/types.ts +++ b/ui/src/lib/api/types.ts @@ -26,6 +26,7 @@ export const CAPABILITIES = [ 'sensor.reset_cursor', 'run.adhoc', 'connection.test', + 'location.republish', 'plan.preview', 'location.manage', 'user.manage', @@ -34,7 +35,10 @@ export const CAPABILITIES = [ ] as const; export type Capability = (typeof CAPABILITIES)[number]; -export type PrincipalKind = 'user' | 'scheduler' | 'sensor' | 'system'; +/** Where a republish got to: the new version once published, or why nothing was. */ +export type RepublishResult = { state: 'pending' | 'published' | 'failed' | 'expired'; generation: number | null; error: string | null }; + +export type PrincipalKind = 'user' | 'service' | 'scheduler' | 'sensor' | 'system'; export type Principal = { kind: PrincipalKind; /** Stable handle, e.g. a user name or `scheduler`. */ @@ -48,7 +52,7 @@ export type CurrentUser = Principal & { role?: BuiltInRole; }; -export type AuthMode = 'oidc' | 'trusted_proxy' | 'password' | 'disabled'; +export type AuthMode = 'oidc' | 'trusted_proxy' | 'password' | 'disabled' | 'keys'; // ---- locations, targets and snapshots ---- @@ -85,7 +89,7 @@ export type LocationTarget = { connectionSummary: string | null; }; -export type LocationHealth = 'healthy' | 'degraded' | 'missing_secrets' | 'falling_back' | 'broken'; +export type LocationHealth = 'healthy' | 'degraded' | 'missing_secrets' | 'discovery_failed' | 'falling_back' | 'broken'; /** A project deployed against exactly one target. Staging and dev are separate locations. */ export type Location = { /** Opaque server-generated UUID; the name is a mutable label. */ diff --git a/ui/src/lib/api/types/operate.ts b/ui/src/lib/api/types/operate.ts index ae8cc3f8a6..98f240d01f 100644 --- a/ui/src/lib/api/types/operate.ts +++ b/ui/src/lib/api/types/operate.ts @@ -38,6 +38,8 @@ export type NodeCounts = { skipped: number; running: number; pending: number; + /** Of `skipped`, the nodes that never ran because the run stopped first: "not run", not "skipped". */ + notRun?: number; }; /** Compute estimate for a finished run; null where the adapter reports no cost. */ @@ -164,7 +166,7 @@ export type RunRow = { cancelRequestedAt: Iso | null; /** Ad-hoc runs: the selection as typed. */ selection: string[]; - /** Nodes a rerun from failure would run; empty when nothing failed. */ + /** How many nodes a rerun from failure would run; zero when every node finished. */ rerunFromFailureCount: number; }; @@ -218,6 +220,12 @@ export type RunNode = { startedAt: Iso | null; endedAt: Iso | null; rowsAffected: number | null; + /** Rows a table rebuilt in full holds, read from warehouse metadata where that is exact and free. */ + tableRows?: number | null; + /** Rows a running node has written so far, where its warehouse reports them. */ + rowsSoFar?: number | null; + /** Why a node that ran changed nothing, such as `unchanged since its last build`. */ + noChangeReason?: string | null; errorCode: string | null; errorMessage: string | null; /** Where in the project the failure points: the model file, and the line when it is known. */ @@ -242,6 +250,8 @@ export type RunNodeError = { export type RunEdge = { from: string; to: string }; export const RECALL_EVENT_TYPES = [ + // A Python node's `ctx.log` line: few, deliberate, kept as events. + 'node_log', 'invocation_started', 'invocation_completed', 'invocation_failed', @@ -286,6 +296,28 @@ export type RunEvent = { statementId: string | null; attempt: number | null; message: string; + /** For `audit_completed`: which check ran, how it came out and how many rows it found. */ + check?: RunEventCheck | null; +}; + +/** A check's result in a run: its name as declared, its outcome, the rows it found, and its identity for its evidence. */ +export type RunEventCheck = { + name: string; + outcome: 'passed' | 'warned' | 'failed' | 'skipped'; + rows: number | null; + /** The check's ID on the Checks page and this result's, to read the rows it found once they are synced. */ + bindingKey: string | null; + resultId: string | null; +}; + +/** A read of a run's output that carries on from the last: lines, the run's `ctx.log` lines and the run's last line. */ +export type RunOutputFollow = { + lines: RunOutputLine[]; + logs: RunEvent[]; + /** The last line read, to carry on from. */ + last: number; + /** Whether `lines` are the newest lines, replacing earlier reads, rather than those after `after`. */ + replaced: boolean; }; export type RunEventPage = { @@ -412,7 +444,44 @@ export type RunOutputLine = { text: string; /** The error the invocation recorded when it failed, rather than a line it printed. */ error: boolean; + /** The node the line is about, when sqb printed it for one. */ + nodeKey?: string | null; + /** A marker in a capped live view: this many earlier lines of the node's output are in the viewer, not here. */ + omitted?: number; +}; + +// ---- a node's bulk output, paged from the output store ---- + +export type NodeOutputLevel = 'info' | 'warn' | 'error'; +/** What the output store's index knows about a node's output, without reading it. */ +export type NodeOutputIndex = { + total: number; + stdout: number; + stderr: number; + bytes: number; + /** Error and warning lines, by line number, from the index. */ + marks: { line: number; level: Exclude; text: string }[]; + /** Still being written: the node is running. */ + live: boolean; +}; +export type NodeOutputLine = { n: number; stream: 'stdout' | 'stderr'; text: string; level: NodeOutputLevel }; +/** A line, or a run of similar lines (the same but for their numbers) folded into one row. */ +export type NodeOutputRow = { kind: 'line'; line: NodeOutputLine } | { kind: 'similar'; from: number; count: number; sample: NodeOutputLine }; +/** Rows covering lines `from` to `to` (exclusive, 1-based). */ +export type NodeOutputPage = { total: number; from: number; to: number; rows: NodeOutputRow[] }; +/** + * A search of a node's output: the next match, and, where the output was small enough to search whole, + * how many lines match and this one's place among them (1-based); null for a large output. + */ +export type NodeOutputSearch = { + count: number | null; + line: number | null; + rank: number | null; + /** Where to search on, when this search stopped part-way through a large output without a match. */ + continueFrom?: number | null; }; +/** The rows a failing check found: a sample, and how many there were in all. */ +export type CheckSample = { columns: string[]; rows: (string | number | null)[][]; total: number }; export type RunInvocation = { invocationId: string; @@ -481,7 +550,7 @@ export type RunDetail = { selection: string[]; /** Why the run is still queued; empty once claimed. */ waits: QueueWait[]; - /** Nodes a rerun from failure would run: the failed ones plus exactly those skipped. */ + /** Nodes a rerun from failure would run: exactly the failed, cancelled, skipped and not-run ones. */ rerunFromFailureNodes: string[]; /** The run this one reruns. */ rerunOf: Run | null; @@ -1095,6 +1164,8 @@ export type SensorEvaluation = { abandonedBecause: AbandonReason | null; /** The operator who skipped the tick's event, so the function wasn't called; `skipReason` is theirs. */ skippedBy: string | null; + /** Why the tick's details are missing, when an earlier release recorded them in a form this one can't read. */ + unreadable: string | null; definitionFingerprint: string; }; diff --git a/ui/src/lib/api/types/platform.ts b/ui/src/lib/api/types/platform.ts index 4c7f5fbfc2..c591f3980c 100644 --- a/ui/src/lib/api/types/platform.ts +++ b/ui/src/lib/api/types/platform.ts @@ -414,6 +414,46 @@ export type Account = Principal & { activeSessions: number; }; +/** An API key of a service account; the server stores only a hash. */ +export type ServiceAccountKey = { + id: string; + /** Non-secret start of the key, shown for identification, e.g. `sqbk_7Qm2xT`. */ + prefix: string; + createdAt: Iso; + /** Who made it; null when the control-store owner did, with the CLI. */ + createdBy: string | null; + /** The last request it authenticated that wasn't refused. */ + lastUsedAt: Iso | null; + /** When a key replaced by a rotation stops working; null for the current key. */ + expiresAt: Iso | null; + /** `imported` keys were chosen by an operator with the CLI's `--key-from-env`. */ + origin: 'issued' | 'imported'; +}; + +/** A principal for automation: roles and audit entries like a person, but signs in only with an API key. */ +export type ServiceAccount = Principal & { + kind: 'service'; + /** What uses it, e.g. "Deploy script in the release pipeline". */ + description: string | null; + /** The built-in role it has everywhere; null when it has none. */ + role: BuiltInRole | null; + createdAt: Iso; + /** Who added it; null when the control-store owner did, with the CLI. */ + createdBy: string | null; + /** The newest use of any of its keys. */ + lastUsedAt: Iso | null; + /** Disabled accounts' keys stop working at once; enabling makes the same keys work again. */ + disabled: boolean; + /** Keys that work, or will once enabled: the current key, then any old key still in a rotation overlap. */ + keys: ServiceAccountKey[]; +}; + +/** A service account to add: its name, what uses it and its role. */ +export type NewServiceAccount = { name: string; description: string | null; role: BuiltInRole }; + +/** A rotation: how many minutes the old key keeps working, or null to stop it at once. */ +export type KeyRotation = { overlapMinutes: number | null }; + /** A person to add who signs in with a password: their sign-in name, first password and a built-in role everywhere, or none for the default role only. */ export type NewPasswordAccount = { name: string; diff --git a/ui/src/lib/components/admin/assignment-list.svelte b/ui/src/lib/components/admin/assignment-list.svelte index 392b9bb32c..7d13d07f7a 100644 --- a/ui/src/lib/components/admin/assignment-list.svelte +++ b/ui/src/lib/components/admin/assignment-list.svelte @@ -4,7 +4,12 @@ import { to } from '$lib/paths'; import TriangleAlertIcon from '@lucide/svelte/icons/triangle-alert'; import RelativeTime from '$lib/components/list/relative-time.svelte'; + import EllipsisIcon from '@lucide/svelte/icons/ellipsis'; import GatedButton from '$lib/components/platform/gated-button.svelte'; + import ConfirmDialog from '$lib/components/platform/confirm-dialog.svelte'; + import MenuSelect from '$lib/components/platform/menu-select.svelte'; + import { buttonVariants } from '$lib/components/ui/button/button.svelte'; + import * as DropdownMenu from '$lib/components/ui/dropdown-menu'; import type { Principal, RoleAssignment, RoleDefinition } from '$lib/api'; import { formatAgo, formatStamp } from '$lib/format/time'; import { lockedHint, rankAssignments, roleHref, roleSummary, scopeWords } from '$lib/platform/access'; @@ -43,6 +48,8 @@ if (!lists.length) return []; return lists[0].filter((r) => r.source === 'built_in' && lists.every((l) => l.some((x) => x.name === r.name))); }); + const whereOptions = $derived([{ value: '', label: 'Every location' }, ...locations.map((l) => ({ value: l.id, label: l.name }))]); + const roleOptions = $derived([{ value: '', label: 'Role…', disabled: true }, ...choices.map((r) => ({ value: r.name, label: r.name, hint: roleSummary(r) }))]); const roleOf = (name: string) => allRoles.find((r) => r.name === name); // A role picked for another place may not be on offer here. $effect(() => { @@ -69,20 +76,27 @@ if (ok) newRole = ''; } - function remove(a: RoleAssignment) { + /** The assignment whose removal waits for its confirmation. */ + let removing = $state(null); + function removal(a: RoleAssignment) { const where = scopeWords(a.scope.locationId, locations); - const message = isOwnLastAdmin(a) - ? `This is YOUR LAST ADMIN ROLE.\n\nRemoving it would immediately take away your access to people, roles, tokens, locations and the audit log, and nobody could undo it from this account. The server refuses this change; another admin has to make it.\n\nSend the request anyway?` - : `Remove ${a.role} from ${principal.displayName} in ${where}?`; - if (!confirm(message)) return; - void act(a.id, () => app.client.deleteRoleAssignment(a.id)); + return isOwnLastAdmin(a) + ? { + title: 'Remove your last admin role?', + body: 'This is your last admin role. Removing it would immediately take away your access to people, roles, tokens, locations and the audit log, and nobody could undo it from this account. The server refuses this change; another admin has to make it. Send the request anyway?' + } + : { title: `Remove ${a.role}?`, body: `${principal.displayName} loses ${a.role} in ${where}.` }; + } + async function remove(a: RoleAssignment) { + await app.client.deleteRoleAssignment(a.id); + onchange(); } const tableColumns: TableColumn[] = [ { id: 'role', label: 'Role', minWidth: 220, truncate: false }, { id: 'where', label: 'Where', width: '160px' }, { id: 'from', label: 'From', width: '170px' }, { id: 'since', label: 'Since', width: '140px' }, - { id: 'action', label: '', width: '170px', align: 'right' } + { id: 'action', label: '', width: '150px', align: 'right' } ]; @@ -106,7 +120,14 @@ {#if a.source === 'manual'} - remove(a)}>Remove + {#if app.can('role.assign')} + + + + (removing = a)}>Remove… + + + {/if} {:else if a.source === 'sso'} See SSO mapping {:else} @@ -119,19 +140,18 @@ {#if app.can('role.assign')}
- - + (newLocation = v)} label="Where" testid="assignment-where" /> + (newRole = v)} label="Role" testid="assignment-role" /> Give role
{/if} {#if error}

{error}

{/if} +{#if removing} + {@const question = removal(removing)} + {@const target = removing} + remove(target)} onclose={() => (removing = null)} /> +{/if} diff --git a/ui/src/lib/components/platform/menu-select.svelte b/ui/src/lib/components/platform/menu-select.svelte new file mode 100644 index 0000000000..bb7a1756f7 --- /dev/null +++ b/ui/src/lib/components/platform/menu-select.svelte @@ -0,0 +1,78 @@ + + + + + + {current?.label ?? value} + + + + next !== value && onchange(next as T)}> + {#each options as o (o.value)} + + + {o.label} + {#if o.hint}{o.hint}{/if} + + + {/each} + + + + + diff --git a/ui/src/lib/components/platform/modal.svelte b/ui/src/lib/components/platform/modal.svelte new file mode 100644 index 0000000000..9c5fb8ee66 --- /dev/null +++ b/ui/src/lib/components/platform/modal.svelte @@ -0,0 +1,75 @@ + + + !next && onclose()}> + + + +
+
+ {title} + {#if description}{description}{/if} +
+ +
+ {@render children()} + {#if footer}{/if} +
+
+
+ + diff --git a/ui/src/lib/components/platform/republish-now.svelte b/ui/src/lib/components/platform/republish-now.svelte new file mode 100644 index 0000000000..d5f94d81a6 --- /dev/null +++ b/ui/src/lib/components/platform/republish-now.svelte @@ -0,0 +1,60 @@ + + +
+ {#if publishing} + + {:else if result?.state === 'published'} + + {:else if result?.state === 'failed'} + + {:else if result?.state === 'expired'} + + {/if} + {#if failure}{failure}{/if} + Republish +
+ + diff --git a/ui/src/lib/components/selection/selection-bar.svelte b/ui/src/lib/components/selection/selection-bar.svelte index 7aad319109..afe2d58eee 100644 --- a/ui/src/lib/components/selection/selection-bar.svelte +++ b/ui/src/lib/components/selection/selection-bar.svelte @@ -31,7 +31,9 @@ names, total, build = true, + copy: offerCopy = true, leading, + trailing, view }: { selection: SelectionState; @@ -41,7 +43,11 @@ total: number; /** Offer Build these. */ build?: boolean; + /** Offer Copy as `sqb build -s …`; off where the next page shows the command anyway. */ + copy?: boolean; leading?: Snippet; + /** After the count, on the same row, such as the run page's quick picks and Plan these. */ + trailing?: Snippet; view?: Snippet; } = $props(); @@ -116,10 +122,11 @@ {:else if selection.evaluation}{selection.evaluation.count.toLocaleString('en')} {noun(selection.evaluation.count, 'node')} {:else}—{/if} - + {#if offerCopy}{/if} {#if build && canBuild} Build these {/if} + {@render trailing?.()} {#if showExcept || view}
diff --git a/ui/src/lib/lineage/member-box-node.svelte b/ui/src/lib/lineage/member-box-node.svelte index f87520860a..9a1293174b 100644 --- a/ui/src/lib/lineage/member-box-node.svelte +++ b/ui/src/lib/lineage/member-box-node.svelte @@ -4,7 +4,7 @@ import { Handle, Position, type NodeProps } from '@xyflow/svelte'; import { to } from '$lib/paths'; import { formatAgo } from '$lib/format/time'; - import { runStatusLabel, runStatusTone } from '$lib/status'; + import { memberRunLabel, runStatusTone } from '$lib/status'; import { app } from '$lib/state/app.svelte'; import type { MemberCardData } from './member-graph'; import { clickGuard } from './click-guard'; @@ -32,8 +32,8 @@ {#if d.nodeCount !== null}· {plural(d.nodeCount, 'node')}{/if} {#if d.lastRun} - - {d.lastRun.startedAt ? formatAgo(d.lastRun.startedAt, app.now) : runStatusLabel[d.lastRun.status]} + + {d.lastRun.startedAt ? formatAgo(d.lastRun.startedAt, app.now) : memberRunLabel(d.lastRun)} {/if} Open job ↗ diff --git a/ui/src/lib/lineage/member-graph.svelte b/ui/src/lib/lineage/member-graph.svelte index 47d1e50321..4f9c16ab94 100644 --- a/ui/src/lib/lineage/member-graph.svelte +++ b/ui/src/lib/lineage/member-graph.svelte @@ -28,7 +28,9 @@ catalog = [], links = new Map(), selection = $bindable(null), - details + details, + initialExpanded = [], + fitWhole = false }: { members: JobGroupMember[]; info: ReadonlyMap; @@ -37,11 +39,16 @@ selection?: MemberSelection | null; /** The page's details panel, toggled from the toolbar as on Lineage. */ details?: { open: boolean; toggle: () => void }; + /** Members open in place when the graph first shows, such as a run's failed member. */ + initialExpanded?: readonly string[]; + /** Open on the whole graph, even when its cards turn compact (a run's graph). */ + fitWhole?: boolean; } = $props(); const nodeTypes = { member: MemberNode, memberBox: MemberBoxNode, asset: AssetNode, folder: FolderNode, folderBox: JobBoxNode }; const edgeTypes = { count: CountEdge }; - let expanded = $state>(new Set()); + // svelte-ignore state_referenced_locally + let expanded = $state>(new Set(initialExpanded)); let openFolders = $state>>(new Map()); /** Selects a member and opens or closes it, from its card or its box's header. */ function toggle(jobKey: string) { @@ -279,6 +286,9 @@ bind:viewport bind:setViewport bind:element={panel} + readable={!fitWhole} + {...fitWhole ? { fitFloor: 0.1 } : {}} + {...fitWhole ? { fitViewOptions: { padding: 0.06, maxZoom: 1, minZoom: 0.1 } } : {}} {nodeTypes} {edgeTypes} nodesDraggable={false} diff --git a/ui/src/lib/lineage/member-node.svelte b/ui/src/lib/lineage/member-node.svelte index c4968aee2d..25202ee500 100644 --- a/ui/src/lib/lineage/member-node.svelte +++ b/ui/src/lib/lineage/member-node.svelte @@ -5,7 +5,7 @@ import { Handle, Position, type NodeProps } from '@xyflow/svelte'; import { to } from '$lib/paths'; import { formatAgo } from '$lib/format/time'; - import { runStatusLabel, runStatusTone } from '$lib/status'; + import { memberRunLabel, runStatusTone } from '$lib/status'; import { app } from '$lib/state/app.svelte'; import type { MemberCardData } from './member-graph'; import CompactFace from '$lib/components/graph/compact-face.svelte'; @@ -47,7 +47,7 @@
{#if d.lastRun} - {runStatusLabel[d.lastRun.status]} + {memberRunLabel(d.lastRun)} {#if when}{when}{/if} {:else} No runs yet diff --git a/ui/src/lib/lineage/status-line.test.ts b/ui/src/lib/lineage/status-line.test.ts index 9c5a021932..2d0d7b9268 100644 --- a/ui/src/lib/lineage/status-line.test.ts +++ b/ui/src/lib/lineage/status-line.test.ts @@ -20,6 +20,12 @@ describe('a card status line on one line', () => { expect(fitStatus(parts, measure, 150)).toEqual({ label: false, driftWord: false }); }); + it('counts the separator and the checks badge as drawn, so a line that measures exactly the room still shortens', () => { + // Inter's widths of these parts in a browser: the line draws 219 px, past the card's 214. + const inter: Measure = (text) => ({ Success: 44, '13m ago': 44, changed: 44, '✕ 1': 16 })[text] ?? 0; + expect(fitStatus({ label: 'Success', when: '13m ago', drift: 'changed', checks: '✕ 1' }, inter)).toEqual({ label: true, driftWord: false }); + }); + it('has the room of a card', () => { expect(STATUS_ROOM).toBe(214); }); diff --git a/ui/src/lib/lineage/status-line.ts b/ui/src/lib/lineage/status-line.ts index 3d5143ca56..7f319bd289 100644 --- a/ui/src/lib/lineage/status-line.ts +++ b/ui/src/lib/lineage/status-line.ts @@ -10,8 +10,10 @@ const GAP = 6; const DOT = 7; /** A drift chip's icon, gap, padding and border around its word. */ const CHIP = 10 + 3 + 2 * 5 + 2; -/** The '·' and its margin before the time when it follows the status word. */ -const SEP = 10; +/** The '·' and its margin before the time when it follows the status word, as drawn. */ +const SEP = 12; +/** What the checks badge draws beyond its measured text: tabular figures, and a ✕ or ✓ from a fallback font. */ +const CHECKS_EXTRA = 3; export type StatusParts = { label?: string; when?: string; drift?: string; checks?: string }; export type StatusFit = { label: boolean; driftWord: boolean }; @@ -23,7 +25,7 @@ export function fitStatus(parts: StatusParts, measure: Measure = measureText, ro parts.label !== undefined ? DOT + (label ? GAP + measure(parts.label, 11, 500) : 0) : null, parts.when ? measure(parts.when, 11, 400) + (parts.label !== undefined ? SEP : 0) : null, parts.drift ? CHIP + (driftWord ? measure(parts.drift, 10.5, 600) : -3) : null, - parts.checks ? measure(parts.checks, 11, 400) : null + parts.checks ? measure(parts.checks, 11, 400) + CHECKS_EXTRA : null ].filter((w): w is number => w !== null); return items.reduce((a, b) => a + b, 0) + GAP * Math.max(0, items.length - 1); }; diff --git a/ui/src/lib/operate/labels.ts b/ui/src/lib/operate/labels.ts index 5e0c8ef8c3..d82f56c2e3 100644 --- a/ui/src/lib/operate/labels.ts +++ b/ui/src/lib/operate/labels.ts @@ -97,7 +97,9 @@ export type WaitPart = { text: string; href?: string; code?: boolean }; /** What went wrong in a finished run, such as "3 failed, 12 skipped"; empty when nothing did. */ export function outcomeCounts(c: NodeCounts): string { - return [c.failed ? `${c.failed} failed` : null, c.skipped ? `${c.skipped} skipped` : null].filter(Boolean).join(', '); + const notRun = c.notRun ?? 0; + const counted = (count: number, word: string) => (count ? `${count} ${word}` : null); + return [counted(c.failed, 'failed'), counted(c.skipped - notRun, 'skipped'), counted(notRun, 'not run')].filter(Boolean).join(', '); } /** `run-4f2a` → `4f2a`, a UUID → its first 8 digits: the short form shown in lists; the full ID stays in links and copies. */ diff --git a/ui/src/lib/platform/access.ts b/ui/src/lib/platform/access.ts index ba4446a2dc..dc135f170a 100644 --- a/ui/src/lib/platform/access.ts +++ b/ui/src/lib/platform/access.ts @@ -88,6 +88,12 @@ export function personHref(principal: { name: string }): string { return `/admin/people/${encodeURIComponent(principal.name)}`; } +/** Where a principal's page is: a service account's panel on People, or a person's own page. */ +export function principalHref(principal: { kind: string; name: string }): string { + if (principal.kind === 'service') return `/admin/people?tab=service-accounts&open=${encodeURIComponent(principal.name)}`; + return personHref(principal); +} + export function roleHref(name: string): string { return `/admin/roles/${encodeURIComponent(name)}`; } diff --git a/ui/src/lib/platform/labels.ts b/ui/src/lib/platform/labels.ts index fbf47e0e67..ee659d6832 100644 --- a/ui/src/lib/platform/labels.ts +++ b/ui/src/lib/platform/labels.ts @@ -21,6 +21,7 @@ export const healthTone: Record = { healthy: 'var(--sb-success)', degraded: 'var(--sb-warning)', missing_secrets: 'var(--sb-error)', + discovery_failed: 'var(--sb-warning)', falling_back: 'var(--sb-warning)', broken: 'var(--sb-error)' }; @@ -29,6 +30,7 @@ export const healthLabel: Record = { healthy: 'Healthy', degraded: 'Needs attention', missing_secrets: 'Missing provider secrets', + discovery_failed: 'Discovery failed', falling_back: 'Running previous version', broken: 'Broken' }; @@ -38,6 +40,7 @@ export const healthHelp: Record = { healthy: 'Loaded and starting scheduled runs', degraded: 'Running, with open problems', missing_secrets: 'A provider setting is missing from the location environment', + discovery_failed: 'A discover function failed at the last publish; its nodes keep their last good items', falling_back: 'The last deploy failed to load; the previous version keeps running', broken: 'Not starting scheduled runs' }; diff --git a/ui/src/lib/platform/permission-catalog.ts b/ui/src/lib/platform/permission-catalog.ts index 2b95945255..b01707106e 100644 --- a/ui/src/lib/platform/permission-catalog.ts +++ b/ui/src/lib/platform/permission-catalog.ts @@ -32,6 +32,7 @@ export const PERMISSIONS: Record = { 'sensor.reset_cursor': { label: 'Reset where a sensor is up to', description: 'Move a sensor’s position so it looks at events again.', risk: 'operate' }, 'run.adhoc': { label: 'Run ad-hoc commands', description: 'Run sqb build and other commands on any selection of nodes outside a declared job, writing to the warehouse.', risk: 'changes_data' }, 'connection.test': { label: 'Test warehouse connections', description: 'Run the connection check from a location.', risk: 'operate' }, + 'location.republish': { label: 'Republish locations', description: 'Ask a location to compile and publish again, which runs its discover functions.', risk: 'operate' }, 'plan.preview': { label: 'Preview build plans', description: 'See what a run would build without running it.', risk: 'read' }, 'location.manage': { label: 'Manage locations and their tokens', description: 'Register locations and create, rotate or revoke their tokens.', risk: 'administer' }, 'user.manage': { label: 'Manage people', description: 'Disable or enable people.', risk: 'administer' }, @@ -97,6 +98,13 @@ const AUDIT_ONLY: Record = { 'principal.created': 'Added person', 'principal.disabled': 'Disabled person', 'principal.enabled': 'Enabled person', + 'service_account.created': 'Added service account', + 'service_account.key_rotated': 'Rotated service account key', + 'service_account.key_revoked': 'Stopped service account key', + 'service_account.disabled': 'Disabled service account', + 'service_account.enabled': 'Enabled service account', + 'service_account.role_changed': 'Changed service account role', + 'snapshot.republished': 'Republished', 'role.assigned': 'Changed role', 'role.revoked': 'Removed role', 'run.acknowledged': 'Acknowledged run', diff --git a/ui/src/lib/platform/sign-out.ts b/ui/src/lib/platform/sign-out.ts index 633654bcdb..b6a42c8d70 100644 --- a/ui/src/lib/platform/sign-out.ts +++ b/ui/src/lib/platform/sign-out.ts @@ -8,7 +8,7 @@ export type SignOut = { kind: 'session' } | { kind: 'link'; href: string } | nul * sign-out. Local development has no sign-in. */ export function signOutFor(bootstrap: Pick | null): SignOut { - if (!bootstrap || bootstrap.authMode === 'disabled') return null; + if (!bootstrap || bootstrap.authMode === 'disabled' || bootstrap.authMode === 'keys') return null; if (bootstrap.authMode !== 'trusted_proxy') return { kind: 'session' }; return bootstrap.logoutUrl ? { kind: 'link', href: bootstrap.logoutUrl } : null; } diff --git a/ui/src/lib/run/cant-run-problem.svelte b/ui/src/lib/run/cant-run-problem.svelte index e4efd80aa1..3467c9f48a 100644 --- a/ui/src/lib/run/cant-run-problem.svelte +++ b/ui/src/lib/run/cant-run-problem.svelte @@ -11,13 +11,18 @@
{title} - provider {entry.provider} needs {variablesText(entry)} + {#if entry.provider} + provider {entry.provider} needs {variablesText(entry)} + {:else} + + sink {entry.sinks?.join(', ')} needs {variablesText(entry)} + {/if} missing secret
{#if entry.nodes.length}
needs
-
{needsText(entry)}
+
{needsText(entry)}
{/if} {#if entry.sinks?.length}
sinks
@@ -70,6 +75,11 @@ dd { margin: 0; } + /* However many nodes one secret stops, the fix below them stays in view. */ + .stopped { + max-height: 7.5em; + overflow: auto; + } code { font-family: var(--font-mono); font-size: 11.5px; diff --git a/ui/src/lib/run/cant-run.test.ts b/ui/src/lib/run/cant-run.test.ts index 318d616818..8ee77021f7 100644 --- a/ui/src/lib/run/cant-run.test.ts +++ b/ui/src/lib/run/cant-run.test.ts @@ -33,9 +33,9 @@ describe('a plan with nodes that cannot run', () => { it('names what the provider stops and how to fix it', () => { expect(needsText(payments)).toBe('raw_payments and the 2 nodes that read it (stg_payments, fct_payments)'); expect(fixText(payments, 'plan again')).toBe( - "set PAYMENTS_API_TOKEN in the location's environment (or its .env), restart the location, then plan again" + 'set PAYMENTS_API_TOKEN in .env, then restart the location (in sqb dev, press r), or in the environment the location (or sqb dev) was started with, then restart it; after that, plan again' ); - expect(fixText({ ...payments, env_file: null }, 'plan again')).toBe("set PAYMENTS_API_TOKEN in the location's environment, restart the location, then plan again"); + expect(fixText({ ...payments, env_file: null }, 'plan again')).toBe('set PAYMENTS_API_TOKEN in the environment the location (or sqb dev) was started with, then restart it; after that, plan again'); }); it('gives each node its reason, readers naming the blocked node they read', () => { @@ -51,13 +51,17 @@ describe('a plan with nodes that cannot run', () => { describe('a run that hit missing secrets', () => { it('reads each provider, its failed nodes and what was skipped because of them', () => { const message = "provider payments_api: PAYMENTS_API_TOKEN not set (missing from the location's environment and from .env)"; + const at = { runId: 'r1', startedAt: null }; expect( - runCantRun([ - { nodeKey: 'source:raw_payments', status: 'failed', errorCode: 'D012', errorMessage: message, skippedBecauseOf: null }, - { nodeKey: 'model:stg_payments', status: 'skipped', errorCode: null, errorMessage: null, skippedBecauseOf: { nodeKey: 'source:raw_payments' } }, - { nodeKey: 'model:fct_payments', status: 'skipped', errorCode: null, errorMessage: null, skippedBecauseOf: { nodeKey: 'model:stg_payments' } }, - { nodeKey: 'model:orders', status: 'failed', errorCode: 'Q001', errorMessage: 'syntax error', skippedBecauseOf: null } - ]) + runCantRun( + [ + { ...at, nodeKey: 'source:raw_payments', status: 'failed', errorCode: 'D012', errorMessage: message, skippedBecauseOf: null }, + { ...at, nodeKey: 'model:stg_payments', status: 'skipped', errorCode: null, errorMessage: null, skippedBecauseOf: { nodeKey: 'source:raw_payments' } }, + { ...at, nodeKey: 'model:fct_payments', status: 'skipped', errorCode: null, errorMessage: null, skippedBecauseOf: { nodeKey: 'model:stg_payments' } }, + { ...at, nodeKey: 'model:orders', status: 'failed', errorCode: 'Q001', errorMessage: 'syntax error', skippedBecauseOf: null } + ], + [{ id: 'r1', statusReason: null }] + ) ).toEqual([{ ...payments, path: '' }]); }); }); diff --git a/ui/src/lib/run/cant-run.ts b/ui/src/lib/run/cant-run.ts index 78a9fdd800..ccfbcffeac 100644 --- a/ui/src/lib/run/cant-run.ts +++ b/ui/src/lib/run/cant-run.ts @@ -1,6 +1,6 @@ // What a plan can't run because a provider is missing secrets, and the words the plan page shows for it. Pure. -import type { PlanCantRun } from '$lib/api'; +import type { PlanCantRun, Run, RunDetail, RunNode } from '$lib/api'; import { plural } from '$lib/format/plural'; import { buildCommand, parseCommand, selectorOf } from './command'; @@ -62,10 +62,14 @@ export function needsText(entry: PlanCantRun): string { return `${users} and the ${plural(entry.readers.length, 'node')} that read ${it} (${entry.readers.map(keyName).join(', ')})`; } -/** How to fix it at the location, then `then`: "plan again" on a plan, "the next run works" on a run. */ +/** + * How to fix it at the location, then `then`: "plan again" on a plan, "the next run works" on a run. A location reads + * its env file again when it restarts, or on `r` under `sqb dev`; only a restart sees a changed environment. + */ export function fixText(entry: PlanCantRun, then: string): string { - const where = entry.env_file ? `the location's environment (or its ${entry.env_file})` : "the location's environment"; - return `set ${variablesText(entry)} in ${where}, restart the location, then ${then}`; + const environment = 'in the environment the location (or sqb dev) was started with, then restart it'; + const file = entry.env_file ? `in ${entry.env_file}, then restart the location (in sqb dev, press r), or ` : ''; + return `set ${variablesText(entry)} ${file}${environment}; after that, ${then}`; } /** One table row: the node, whether it uses the provider or only reads a node that does, and why it can't run. */ @@ -91,28 +95,82 @@ export function cantRunRows(entries: PlanCantRun[], upstreamOf: (key: string) => return [...rows.values()]; } -/** A run node's `D012` message, as a worker writes it: `provider X: A, B not set (missing from the location's environment and from .env)`. */ +/** + * A run node's `D012` message, as a worker writes it and the server lists it: `provider X: A, B not set (missing from + * the location's environment and from .env)`. Error redaction can take a variable of a provider named like a secret + * (`orders_api_key: [REDACTED]`), so the variables come from the run's status reason where it has them. + */ const MISSING_SECRET_MESSAGE = /^provider (\S+): (.+) not set \(missing from (.+)\)$/; +/** + * The status reason of a run that stopped on missing secrets: `Couldn't run: provider X needs A, B; sink S needs C; + * every run uses sinks (missing from the location's environment and from .env); nothing ran`, perhaps with a note after it. + */ +const MISSING_SECRET_REASON = /^Couldn't run: (.+) \(missing from (.+)\); nothing ran/; + +/** The env file in where a secret was looked for: `.env` in `the location's environment and from .env`. */ +const envFileIn = (places: string) => /environment and from (.+)$/.exec(places)?.[1] ?? null; + +type Refusal = { envFile: string | null; providers: Map; sinks: { name: string; variables: string[] }[] }; + +function refusalOf(reason: string | null): Refusal | null { + const match = MISSING_SECRET_REASON.exec(reason ?? ''); + if (!match) return null; + const refusal: Refusal = { envFile: envFileIn(match[2]), providers: new Map(), sinks: [] }; + for (const part of match[1].split('; ')) { + const provider = /^provider (\S+) needs (.+)$/.exec(part); + if (provider) refusal.providers.set(provider[1], provider[2].split(', ')); + const sink = /^sink (.+) needs (.+)$/.exec(part); + if (sink) refusal.sinks.push({ name: sink[1], variables: sink[2].split(', ') }); + } + return refusal.providers.size || refusal.sinks.length ? refusal : null; +} + /** The run's nodes, as much of them as this needs. */ -type RunNodeFacts = { nodeKey: string; status: string; errorCode: string | null; errorMessage: string | null; skippedBecauseOf: { nodeKey: string } | null }; +type RunNodeFacts = Pick & { skippedBecauseOf: { nodeKey: string } | null }; /** - * What a run couldn't run because a provider was missing secrets, read from its nodes: each provider's failed - * nodes, and the nodes skipped because of them, directly or through another skipped node. + * What runs couldn't run because providers were missing secrets: from each run's status reason, the providers, their + * variables and any sinks, which fail no node; from its failed nodes' messages, who uses which provider; and the + * nodes skipped because of those, directly or through another skipped node. Only `runs` the nodes belong to count, + * so a member's superseded attempt adds nothing. A sink whose provider no node uses has no provider name to show. */ -export function runCantRun(nodes: RunNodeFacts[]): PlanCantRun[] { - const byProvider = new Map(); +export function runCantRun(nodes: RunNodeFacts[], runs: Pick[]): PlanCantRun[] { + const shown = new Set(nodes.map((node) => node.runId)); + const entries = new Map(); + const entryOf = (id: string, provider: string, variables: string[], envFile: string | null) => { + const entry = entries.get(id) ?? { reason: 'missing_secret', provider, path: '', variables: [], nodes: [], readers: [], sinks: [], env_file: envFile }; + entry.variables = [...new Set([...entry.variables, ...variables])]; + entries.set(id, entry); + return entry; + }; + const refusals = new Map(); + for (const run of runs) { + const refusal = shown.has(run.id) ? refusalOf(run.statusReason) : null; + if (!refusal) continue; + refusals.set(run.id, refusal); + for (const [provider, variables] of refusal.providers) entryOf(provider, provider, variables, refusal.envFile); + for (const { name, variables } of refusal.sinks) { + const wanted = variables.join(', '); + const provider = [...refusal.providers].find(([, own]) => own.join(', ') === wanted)?.[0] ?? ''; + const entry = entryOf(provider || `sink:${wanted}`, provider, variables, refusal.envFile); + if (!entry.sinks?.includes(name)) entry.sinks = [...(entry.sinks ?? []), name]; + } + } + const users = new Map>(); const owner = new Map(); for (const node of nodes) { - if (node.status !== 'failed' || node.errorCode !== 'D012' || !node.errorMessage) continue; - const match = MISSING_SECRET_MESSAGE.exec(node.errorMessage); - if (!match) continue; - const [, provider, variables, places] = match; - const envFile = /and from (.+)$/.exec(places)?.[1] ?? null; - const entry = byProvider.get(provider) ?? { reason: 'missing_secret', provider, path: '', variables: variables.split(', '), nodes: [], readers: [], sinks: [], env_file: envFile }; - entry.nodes.push(node.nodeKey); - byProvider.set(provider, entry); + if (node.status !== 'failed' || node.errorCode !== 'D012') continue; + const refusal = refusals.get(node.runId); + const said = node.errorMessage ? MISSING_SECRET_MESSAGE.exec(node.errorMessage) : null; + // Without a message, as once history is pruned, only a run missing one provider's secrets says whose it was. + const provider = said?.[1] ?? (!node.startedAt && refusal?.providers.size === 1 ? [...refusal.providers.keys()][0] : null); + if (!provider) continue; + const variables = refusal?.providers.get(provider) ?? said?.[2].split(', ') ?? []; + const entry = entryOf(provider, provider, variables, refusal?.envFile ?? (said ? envFileIn(said[3]) : null)); + const own = users.get(entry) ?? new Set(); + if (!own.has(node.nodeKey)) entry.nodes.push(node.nodeKey); + users.set(entry, own.add(node.nodeKey)); owner.set(node.nodeKey, entry); } let added = true; @@ -127,5 +185,8 @@ export function runCantRun(nodes: RunNodeFacts[]): PlanCantRun[] { added = true; } } - return [...byProvider.values()]; + return [...entries.values()]; } + +/** The run page's Couldn't run blocks: its nodes, with the status reasons of the run and, for a group, its job runs. */ +export const runDetailCantRun = (detail: Pick) => runCantRun(detail.nodes, [detail.run, ...detail.children]); diff --git a/ui/src/lib/status.ts b/ui/src/lib/status.ts index ffdbf304df..24d7a775eb 100644 --- a/ui/src/lib/status.ts +++ b/ui/src/lib/status.ts @@ -1,5 +1,11 @@ import { shortName } from '$lib/build-area/labels'; -import type { CheckOutcome, NodeCounts, NodeOutcome, StaleReason, RunKind, RunOrigin, RunStatus, TickOutcome, TriggerState } from '$lib/api/types'; +import type { CheckOutcome, NodeCounts, NodeOutcome, StaleReason, RunKind, RunNodeStatus, RunOrigin, RunStatus, TickOutcome, TriggerState } from '$lib/api/types'; + +/** The node states a rerun from failure runs, as the server's `UNFINISHED_NODE_STATUSES`. */ +export const UNFINISHED_NODE_STATUSES: readonly RunNodeStatus[] = ['failed', 'skipped', 'cancelled', 'not_run']; + +/** Whether a rerun from failure runs a node in this state. */ +export const isUnfinishedNode = (status: RunNodeStatus) => UNFINISHED_NODE_STATUSES.includes(status); export const runStatusTone: Record = { queued: 'var(--sb-text-faint)', @@ -18,6 +24,11 @@ export const runStatusTone: Record = { /** A finished run that let error-severity audit failures through instead of failing: it reads as a success with a warning. */ export const ignoresAuditFailures = (status: RunStatus, ignored: number) => (status === 'success' || status === 'warn') && ignored > 0; +/** A group member's run, as its card says it: one that never started is "Not started", never "Skipped". */ +export function memberRunLabel(r: { status: RunStatus; startedAt: string | null }): string { + return r.status === 'skipped' && !r.startedAt ? 'Not started' : runStatusLabel[r.status]; +} + export const runStatusLabel: Record = { queued: 'Queued', launched: 'Starting', diff --git a/ui/src/routes/admin/audit/+page.svelte b/ui/src/routes/admin/audit/+page.svelte index bd852af60f..35ac52ba08 100644 --- a/ui/src/routes/admin/audit/+page.svelte +++ b/ui/src/routes/admin/audit/+page.svelte @@ -90,7 +90,7 @@ - {#if e.actor.kind === 'user' && linksPeople}{e.actor.name}{:else}{e.actor.name}{/if} + {#if e.actor.kind === 'user' && linksPeople}{e.actor.name}{:else if e.actor.kind === 'service' && linksPeople}{e.actor.name}{:else}{e.actor.name}{/if}
{e.ip}
diff --git a/ui/src/routes/admin/people/+page.svelte b/ui/src/routes/admin/people/+page.svelte index fd6c17b296..fef9abd90c 100644 --- a/ui/src/routes/admin/people/+page.svelte +++ b/ui/src/routes/admin/people/+page.svelte @@ -26,9 +26,26 @@ import AddPersonPanel from './add-person-panel.svelte'; import PersonPanel from './person-panel.svelte'; import RoleSelect from './role-select.svelte'; - import { defaultRoleOf, isLastAdmin } from './utils'; + import { goto } from '$app/navigation'; + import { page } from '$app/state'; + import PageTabs from '$lib/components/platform/page-tabs.svelte'; + import ServiceAccountsTab from './service-accounts-tab.svelte'; + import { createServiceAccountsState } from './service-accounts.svelte'; + import type { PeopleTab } from './types'; + import { defaultRoleOf, isLastAdmin, parsePeopleTab } from './utils'; const people = createAccountTable('user'); + // Service accounts sit in a tab beside People; servers without them show People alone. + const hasServiceAccounts = $derived(app.client.supports('listServiceAccounts')); + const tab = $derived(hasServiceAccounts ? parsePeopleTab(page.url.searchParams.get('tab')) : 'people'); + const sa = createServiceAccountsState(() => page.url.searchParams.get('open')); + function selectTab(value: PeopleTab) { + const url = new URL(page.url); + url.searchParams.delete('open'); + if (value === 'people') url.searchParams.delete('tab'); + else url.searchParams.set('tab', value); + void goto(url, { replaceState: true, noScroll: true, keepFocus: true }); + } const d = people.directory; const allowed = $derived(app.can('user.manage') || app.can('role.assign')); const locations = $derived(app.bootstrap?.locations ?? []); @@ -50,7 +67,12 @@ function open(e: MouseEvent, a: Account) { if ((e.target as Element).closest('a, button, input, select, label, [data-control]')) return; if (e.metaKey || e.ctrlKey || e.button === 1) openRow(e, personHref(a)); - else pick(a.name); + else toggle(a.name); + } + /** A click on the open person's row closes their panel, as on Service accounts. */ + function toggle(name: string) { + if (selected === name && !adding) selected = null; + else pick(name); } /** Open a person's panel in place of whatever panel is open. */ function pick(name: string) { @@ -76,12 +98,24 @@ - d.refresh()} /> + (tab === 'service-accounts' ? sa.list.refresh() : d.refresh())} /> {#if !allowed} - + {:else} + {#if hasServiceAccounts} + tab, selectTab} + tabs={[ + { value: 'people', label: 'People', count: d.accounts.data ? people.accounts.length : undefined }, + { value: 'service-accounts', label: 'Service accounts', count: sa.list.data?.length, title: 'Scripts and automation that call SQLBuild with an API key' } + ]} + /> + {/if} + {#if tab === 'service-accounts'} + + {:else} {#snippet filters()} ({ value: r, label: r }))} /> @@ -107,7 +141,7 @@
- +
{a.name} · {a.source === 'oidc' ? 'SSO' : a.source ? accountSourceLabel[a.source] : 'no password'}
@@ -144,6 +178,7 @@ {/if}
{/if} +{/if} diff --git a/ui/src/routes/admin/people/api/account.ts b/ui/src/routes/admin/people/api/account.ts index 187437a485..c45269588c 100644 --- a/ui/src/routes/admin/people/api/account.ts +++ b/ui/src/routes/admin/people/api/account.ts @@ -16,18 +16,9 @@ export async function changeRole( for (const id of change.revoke) await app.client.deleteRoleAssignment(id); } -/** Enable or disable an account once its person confirms; false when they cancel. */ -export async function toggleAccount(a: Account): Promise { - const sessions = - a.activeSessions === 1 - ? "their 1 signed-in session ends" - : `their ${a.activeSessions} signed-in sessions end`; - const ask = a.disabled - ? `Enable ${a.displayName} (${a.name})? They can sign in again.` - : `Disable ${a.displayName} (${a.name})? They can't sign in any more, in the browser or with sqb login, and ${sessions} now.`; - if (!confirm(ask)) return false; +/** Enable a disabled account, or disable an enabled one. */ +export async function setAccountEnabled(a: Account): Promise { await (a.disabled ? app.client.enableAccount(a.name) : app.client.disableAccount(a.name)); - return true; } diff --git a/ui/src/routes/admin/people/api/index.ts b/ui/src/routes/admin/people/api/index.ts index 7aef69428d..445298711c 100644 --- a/ui/src/routes/admin/people/api/index.ts +++ b/ui/src/routes/admin/people/api/index.ts @@ -1 +1 @@ -export { changeRole, toggleAccount } from "./account"; +export { changeRole, setAccountEnabled } from "./account"; diff --git a/ui/src/routes/admin/people/key-reveal.svelte b/ui/src/routes/admin/people/key-reveal.svelte new file mode 100644 index 0000000000..7d5758c7be --- /dev/null +++ b/ui/src/routes/admin/people/key-reveal.svelte @@ -0,0 +1,56 @@ + + +
+

Store it now: it won't be shown again. SQLBuild keeps only a hash of it.

+
+ {secret} + +
+ {#if failed}{/if} +
+ + diff --git a/ui/src/routes/admin/people/person-panel.svelte b/ui/src/routes/admin/people/person-panel.svelte index 4b2a5ff06b..b1a52f5b48 100644 --- a/ui/src/routes/admin/people/person-panel.svelte +++ b/ui/src/routes/admin/people/person-panel.svelte @@ -4,35 +4,27 @@ import type { Account, RoleAssignment, RoleDefinition } from '$lib/api'; import Button from '$lib/components/ui/button/button.svelte'; import StatusLabel from '$lib/components/list/status-label.svelte'; - import GatedButton from '$lib/components/platform/gated-button.svelte'; import AssignmentList from '$lib/components/admin/assignment-list.svelte'; import { formatAgo, formatStamp } from '$lib/format/time'; import { to } from '$lib/paths'; import { personHref } from '$lib/platform/access'; - import { accountSourceLabel, errorMessage } from '$lib/platform/labels'; + import { accountSourceLabel } from '$lib/platform/labels'; import { app } from '$lib/state/app.svelte'; - import { toggleAccount } from './api'; + import AccountMenu from './account-menu.svelte'; // A person at a glance beside the list: their roles and enable/disable; their full page keeps effective access. type Props = { account: Account; assignments: RoleAssignment[]; rolesByLocation: Map; onchange: () => void; onclose: () => void }; let { account, assignments, rolesByLocation, onchange, onclose }: Props = $props(); - let busy = $state(false); - let error = $state(null); - async function toggle() { - busy = true; - error = null; - try { - if (await toggleAccount(account)) onchange(); - } catch (e) { - error = errorMessage(e); - } finally { - busy = false; - } + /** Escape closes the panel, but not when it closes a menu or a dialog first. */ + function escape(e: KeyboardEvent) { + if (e.key !== 'Escape' || e.defaultPrevented) return; + if ((e.target as Element | null)?.closest?.('[role="menu"], [role="dialog"]')) return; + onclose(); } - e.key === 'Escape' && onclose()} /> +
+
Last active {account.lastSeenAt ? formatAgo(account.lastSeenAt, app.now) : 'never'} - - {#if account.name === app.user?.name} - You - {:else} - {account.disabled ? 'Enable' : 'Disable'} - {/if} - + {#if account.name === app.user?.name}You{/if}
- {#if error}

{error}

{/if}

Roles

{#if app.can('role.assign')} @@ -112,11 +98,6 @@ font-family: var(--font-mono); font-size: 12px; } - .err { - margin: 0; - color: var(--sb-error); - font-size: 12.5px; - } .full { color: var(--primary); font-size: 12.5px; diff --git a/ui/src/routes/admin/people/role-select.svelte b/ui/src/routes/admin/people/role-select.svelte index 15cb35e13d..a5d8c28548 100644 --- a/ui/src/routes/admin/people/role-select.svelte +++ b/ui/src/routes/admin/people/role-select.svelte @@ -1,5 +1,7 @@ {#if choice.kind === 'mixed'} @@ -46,15 +60,21 @@ {choice.role === 'none' ? 'No role' : choice.role} {:else} - + {#if lastAdmin}last admin{/if} {#if error}{/if} + {#if promoting} + apply('admin')} + onclose={() => (promoting = false)} + /> + {/if} {/if} diff --git a/ui/src/routes/admin/people/service-account-panel.svelte b/ui/src/routes/admin/people/service-account-panel.svelte new file mode 100644 index 0000000000..a6fe5a8639 --- /dev/null +++ b/ui/src/routes/admin/people/service-account-panel.svelte @@ -0,0 +1,261 @@ + + + + + + + sa.list.refresh()} onclose={() => (rotating = false)} /> +{#if confirming} + (confirming = null)} /> +{/if} + + diff --git a/ui/src/routes/admin/people/service-accounts-tab.svelte b/ui/src/routes/admin/people/service-accounts-tab.svelte new file mode 100644 index 0000000000..3e32180b67 --- /dev/null +++ b/ui/src/routes/admin/people/service-accounts-tab.svelte @@ -0,0 +1,175 @@ + + + + {#snippet actions()} + {#if canAdd}{/if} + {/snippet} + +
+ a.name} resource={sa.list} empty="No service accounts match."> + {#snippet emptyRow()} + {#if !sa.accounts.length && sa.list.data} + + +
+ +
No service accounts yet
+

A service account lets a script or system call SQLBuild with an API key, such as a deploy that republishes after each release. Its actions appear in the audit log under its own name.

+ {#if canAdd} + + {/if} +

From a terminal: sqb admin create-service-account <name> --role <role>

+
+ + + {:else} + No service accounts match. + {/if} + {/snippet} + {#snippet row(a)} + {@const status = serviceState(a)} + {@const key = currentKey(a)} + {@const old = oldKey(a)} + onrow(e, a)} data-testid="service-account-row"> + +
+ +
+ + {#if a.description}
{a.description}
{/if} +
+
+ + + {a.role ?? 'No role'} + + {#if key}{key.prefix}…{:else}No key{/if} + {#if old?.expiresAt} +
{old.prefix}… stops {formatIn(old.expiresAt, app.now)}
+ {/if} + + + + + {/snippet} +
+ {#if sa.selectedAccount} + + {/if} +
+ { + sa.list.refresh(); + sa.open(name); + }} + onclose={() => sa.setAdding(false)} +/> + + diff --git a/ui/src/routes/admin/people/service-accounts.svelte.ts b/ui/src/routes/admin/people/service-accounts.svelte.ts new file mode 100644 index 0000000000..75d3d47e18 --- /dev/null +++ b/ui/src/routes/admin/people/service-accounts.svelte.ts @@ -0,0 +1,54 @@ +import { untrack } from "svelte"; +import type { ServiceAccount } from "$lib/api"; +import { app } from "$lib/state/app.svelte"; +import { createResource } from "$lib/state/resource.svelte"; + +/** The Service accounts tab: the list and the open panel. Create during component initialisation. */ +export function createServiceAccountsState(open: () => string | null) { + // Only read where the server has them and the person may see them; the page shows why not otherwise. + const list = createResource((client) => + client.supports("listServiceAccounts") && + (app.can("user.manage") || app.can("role.assign")) + ? client.listServiceAccounts() + : Promise.resolve([] as ServiceAccount[]), + ); + /** The service account whose panel is open, first from `&open=`. */ + let selected = $state(untrack(open)); + let adding = $state(false); + + const accounts = $derived(list.data ?? []); + const selectedAccount = $derived( + selected ? (accounts.find((a) => a.name === selected) ?? null) : null, + ); + + return { + list, + get accounts() { + return accounts; + }, + get selected() { + return selected; + }, + get selectedAccount() { + return selectedAccount; + }, + get adding() { + return adding; + }, + /** Open a service account's panel, or close it when it is already open, as rows do on People. */ + toggle(name: string) { + selected = selected === name ? null : name; + }, + open(name: string) { + selected = name; + }, + close() { + selected = null; + }, + setAdding(value: boolean) { + adding = value; + }, + }; +} + +export type ServiceAccountsState = ReturnType; diff --git a/ui/src/routes/admin/people/service-activity.svelte b/ui/src/routes/admin/people/service-activity.svelte new file mode 100644 index 0000000000..9e0ded6170 --- /dev/null +++ b/ui/src/routes/admin/people/service-activity.svelte @@ -0,0 +1,88 @@ + + +{#if !app.can('audit.view')} +

Seeing activity needs “See the audit log” (audit.view).

+{:else if entries.data?.length} + + All activity → +{:else if entries.data} +

Nothing yet.

+{/if} + + diff --git a/ui/src/routes/admin/people/types.ts b/ui/src/routes/admin/people/types.ts index a61f32428c..5a6b08bd69 100644 --- a/ui/src/routes/admin/people/types.ts +++ b/ui/src/routes/admin/people/types.ts @@ -16,3 +16,12 @@ export type RoleChoice = /** What changing a row's role does: give the new role everywhere, then take back the assignments it replaces. */ export type RoleChange = { give: BuiltinRole | null; revoke: string[] }; + +/** The People page's tabs; `service-accounts` is `?tab=service-accounts`. */ +export type PeopleTab = "people" | "service-accounts"; + +/** When a rotation stops the old key: now, or after this many minutes. */ +export type OverlapChoice = "now" | "15" | "60" | "1440"; + +/** How a service account row reads: working, part-way through a rotation, disabled, or not used yet. */ +export type ServiceState = "active" | "rotating" | "disabled" | "unused"; diff --git a/ui/src/routes/admin/people/utils/account-toggle.test.ts b/ui/src/routes/admin/people/utils/account-toggle.test.ts new file mode 100644 index 0000000000..53d5e9a391 --- /dev/null +++ b/ui/src/routes/admin/people/utils/account-toggle.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import type { Account } from "$lib/api"; +import { accountToggle } from "./account-toggle"; + +const account = (extra: Partial) => + ({ + kind: "user", + name: "morgan", + displayName: "Morgan Diaz", + disabled: false, + activeSessions: 2, + ...extra, + }) as Account; + +describe("accountToggle", () => { + it("asks before disabling, naming the sessions that end, and enabling is not destructive", () => { + expect([ + accountToggle(account({})), + accountToggle(account({ activeSessions: 1 })).body, + accountToggle(account({ disabled: true })), + ]).toEqual([ + { + title: "Disable Morgan Diaz?", + body: "Morgan Diaz (morgan) can't sign in any more, in the browser or with sqb login, and their 2 signed-in sessions end now.", + confirm: "Disable", + destructive: true, + }, + "Morgan Diaz (morgan) can't sign in any more, in the browser or with sqb login, and their 1 signed-in session ends now.", + { + title: "Enable Morgan Diaz?", + body: "Morgan Diaz (morgan) can sign in again.", + confirm: "Enable", + destructive: false, + }, + ]); + }); +}); diff --git a/ui/src/routes/admin/people/utils/account-toggle.ts b/ui/src/routes/admin/people/utils/account-toggle.ts new file mode 100644 index 0000000000..067707dfa3 --- /dev/null +++ b/ui/src/routes/admin/people/utils/account-toggle.ts @@ -0,0 +1,27 @@ +import type { Account } from "$lib/api"; + +/** What the Disable or Enable confirmation says for `a`; disabling is the destructive one. */ +export function accountToggle(a: Account): { + title: string; + body: string; + confirm: string; + destructive: boolean; +} { + if (a.disabled) + return { + title: `Enable ${a.displayName}?`, + body: `${a.displayName} (${a.name}) can sign in again.`, + confirm: "Enable", + destructive: false, + }; + const sessions = + a.activeSessions === 1 + ? "their 1 signed-in session ends" + : `their ${a.activeSessions} signed-in sessions end`; + return { + title: `Disable ${a.displayName}?`, + body: `${a.displayName} (${a.name}) can't sign in any more, in the browser or with sqb login, and ${sessions} now.`, + confirm: "Disable", + destructive: true, + }; +} diff --git a/ui/src/routes/admin/people/utils/index.ts b/ui/src/routes/admin/people/utils/index.ts index f0f2e877ba..28097de1b2 100644 --- a/ui/src/routes/admin/people/utils/index.ts +++ b/ui/src/routes/admin/people/utils/index.ts @@ -5,3 +5,16 @@ export { roleChange, roleChoice, } from "./role-choice"; +export { + OVERLAP_CHOICES, + SERVICE_STATE_LABEL, + currentKey, + keyFacts, + nameProblem, + oldKey, + overlapMinutes, + parsePeopleTab, + serviceState, + statusLine, +} from "./service-accounts"; +export { accountToggle } from "./account-toggle"; diff --git a/ui/src/routes/admin/people/utils/service-accounts.test.ts b/ui/src/routes/admin/people/utils/service-accounts.test.ts new file mode 100644 index 0000000000..0eaf84f406 --- /dev/null +++ b/ui/src/routes/admin/people/utils/service-accounts.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; +import type { ServiceAccount, ServiceAccountKey } from "$lib/api"; +import { keyFacts, nameProblem, statusLine } from "./service-accounts"; + +const NOW = Date.parse("2026-11-21T12:00:00Z"); +const ago = (minutes: number) => new Date(NOW - minutes * 60_000).toISOString(); +const ahead = (minutes: number) => new Date(NOW + minutes * 60_000).toISOString(); + +function key(extra: Partial = {}): ServiceAccountKey { + return { + id: "k", + prefix: "sqbk_Q7m2xT", + createdAt: ago(13), + createdBy: null, + lastUsedAt: null, + expiresAt: null, + origin: "issued", + ...extra, + }; +} + +function account(extra: Partial = {}): ServiceAccount { + return { + kind: "service", + name: "orders-deploy", + displayName: "orders-deploy", + description: null, + role: "developer", + createdAt: ago(600), + createdBy: null, + lastUsedAt: ago(6), + disabled: false, + keys: [key()], + ...extra, + }; +} + +describe("statusLine", () => { + it("names the state first, then when it was used or when the old key stops", () => { + expect([ + statusLine(account(), NOW), + statusLine(account({ keys: [key(), key({ expiresAt: ahead(47) })] }), NOW), + statusLine(account({ disabled: true }), NOW), + statusLine(account({ lastUsedAt: null }), NOW), + ]).toEqual([ + "Active · used 6m ago", + "Rotating · old key stops in 47m", + "Disabled · used 6m ago", + "Not used yet", + ]); + }); +}); + +describe("keyFacts", () => { + it("gives a key's age and last use, and says when it was imported", () => { + expect([ + keyFacts(key(), NOW), + keyFacts(key({ origin: "imported", lastUsedAt: ago(2) }), NOW), + ]).toEqual([ + "created 13m ago · used never", + "imported 13m ago · used 2m ago", + ]); + }); +}); + +describe("nameProblem", () => { + it("accepts what the server accepts and explains the rest", () => { + expect( + ["orders-deploy", "", "Orders", "1st", "a", "ci runner"].map( + nameProblem, + ), + ).toEqual([ + null, + null, + "Start with a lowercase letter.", + "Start with a lowercase letter.", + "Use 2 to 63 characters.", + "Use lowercase letters, digits, - and _ only.", + ]); + }); +}); diff --git a/ui/src/routes/admin/people/utils/service-accounts.ts b/ui/src/routes/admin/people/utils/service-accounts.ts new file mode 100644 index 0000000000..25cb84b154 --- /dev/null +++ b/ui/src/routes/admin/people/utils/service-accounts.ts @@ -0,0 +1,71 @@ +import type { ServiceAccount, ServiceAccountKey } from "$lib/api"; +import { formatAgo, formatIn } from "$lib/format/time"; +import type { OverlapChoice, PeopleTab, ServiceState } from "../types"; + +/** How long the old key keeps working after a rotation; `now` stops it at once. */ +export const OVERLAP_CHOICES: readonly { value: OverlapChoice; label: string }[] = [ + { value: "now", label: "Now" }, + { value: "15", label: "In 15 minutes" }, + { value: "60", label: "In 1 hour" }, + { value: "1440", label: "In 24 hours" }, +]; + +/** The overlap a rotation asks for, in minutes, or null for none. */ +export function overlapMinutes(choice: OverlapChoice): number | null { + return choice === "now" ? null : Number(choice); +} + +/** The People page's tab from `?tab=`; anything else is People. */ +export function parsePeopleTab(value: string | null): PeopleTab { + return value === "service-accounts" ? value : "people"; +} + +/** The key new requests should use. */ +export function currentKey(a: ServiceAccount): ServiceAccountKey | null { + return a.keys.find((k) => k.expiresAt === null) ?? null; +} + +/** The key a rotation replaced, while it still works. */ +export function oldKey(a: ServiceAccount): ServiceAccountKey | null { + return a.keys.find((k) => k.expiresAt !== null) ?? null; +} + +export function serviceState(a: ServiceAccount): ServiceState { + if (a.disabled) return "disabled"; + if (oldKey(a)) return "rotating"; + return a.lastUsedAt ? "active" : "unused"; +} + +export const SERVICE_STATE_LABEL: Record = { + active: "Active", + rotating: "Rotating", + disabled: "Disabled", + unused: "Not used yet", +}; + +/** The panel's one status line, e.g. "Active · used 6m ago" or "Rotating · old key stops in 47m". */ +export function statusLine(a: ServiceAccount, now: number): string { + const state = serviceState(a); + const old = oldKey(a); + if (state === "rotating" && old) + return `Rotating · old key stops ${formatIn(old.expiresAt, now)}`; + if (state === "unused") return "Not used yet"; + return `${SERVICE_STATE_LABEL[state]} · used ${formatAgo(a.lastUsedAt, now)}`; +} + +/** A key's line in the panel: when it was created and last used. */ +export function keyFacts(k: ServiceAccountKey, now: number): string { + const used = k.lastUsedAt ? formatAgo(k.lastUsedAt, now) : "never"; + return `${k.origin === "imported" ? "imported" : "created"} ${formatAgo(k.createdAt, now)} · used ${used}`; +} + +/** Why a new service account's name won't do, or null; the server checks the same and that it's free. */ +export function nameProblem(name: string): string | null { + const n = name.trim(); + if (!n) return null; + if (!/^[a-z]/.test(n)) return "Start with a lowercase letter."; + if (!/^[a-z][a-z0-9_-]*$/.test(n)) + return "Use lowercase letters, digits, - and _ only."; + if (n.length < 2 || n.length > 63) return "Use 2 to 63 characters."; + return null; +} diff --git a/ui/src/routes/admin/roles/[name]/+page.svelte b/ui/src/routes/admin/roles/[name]/+page.svelte index 3a8b1d27b7..44dd1b6881 100644 --- a/ui/src/routes/admin/roles/[name]/+page.svelte +++ b/ui/src/routes/admin/roles/[name]/+page.svelte @@ -1,4 +1,5 @@ + +
+ {#each shown as c (c.id)} + {@const st = statementOf(c)} +
+ {GLYPH[c.outcome]} + {c.name} + {c.outcome}{#if c.count != null}{` · ${c.count.toLocaleString('en-GB')} ${c.noun} (${SEVERITY[c.outcome]})`}{/if} + + {#if c.statementId}{/if} + {#if (c.outcome === 'failed' || c.outcome === 'warned') && c.statementId && app.client.getCheckSample}{/if} + +
+ {#if openSql.has(c.id) && st} + +
onstatement(c.statementId!) : undefined} />
+ {/if} + {#if openRows.has(c.id) && c.statementId} + {@const got = sample[c.statementId]} +
+ {#if got?.state === 'ok' && got.value} + + + {#each got.value.columns as col (col)}{/each} + + {#each got.value.rows as row, i (i)}{#each row as v, j (j)}{/each}{/each} + +
{col}
{v ?? 'null'}
+

{got.value.rows.length < got.value.total ? `${got.value.rows.length} of ${got.value.total.toLocaleString('en-GB')} failing rows` : `${got.value.total.toLocaleString('en-GB')} failing rows`}

+ {:else if got?.state === 'ok'}

No sample was kept.

+ {:else if got?.state === 'error'}

Couldn't load the rows: {got.message}

+ {:else}

Loading…

{/if} +
+ {/if} + {/each} + {#if hidden > 0 || all} + + {/if} +
+ + diff --git a/ui/src/routes/runs/[id]/failures-panel.svelte b/ui/src/routes/runs/[id]/failures-panel.svelte index d15baa09cb..0fd0998923 100644 --- a/ui/src/routes/runs/[id]/failures-panel.svelte +++ b/ui/src/routes/runs/[id]/failures-panel.svelte @@ -1,102 +1,100 @@ +{#snippet line(n: RunNode)} + {@const key = `${n.runId}/${n.nodeKey}`} + {@const loaded = view.nodeError(n)} + {@const where = place(n)} + {@const detail = errorTextOf(n, loaded)} + {@const traceback = tracebackOf(detail)} +
  • + + + {#if open.has(key)} + {@const failure = view.nodeErrorFailure(n)} + {@const failedQueries = view.statements.filter((q) => q.nodeKey === n.nodeKey && q.runId === n.runId && q.status === 'failed')} +
    + {#if where} +
    {where} + {#if n.runId !== view.run?.id}Open its job run{/if} +
    + {/if} + + {#if traceback} + view.openCode(n.nodeKey, line)} /> + {:else if failedQueries.length} + {#each failedQueries as q (q.id)} view.showStatement(q.id, n.nodeKey)} />{/each} + {:else if detail} +
    {detail}
    + {:else if failure} +

    {failure}

    + {:else if loaded} +

    No error text was recorded for this node.

    + {:else if view.errorsReadable} +

    Loading the error…

    + {/if} +
    + {/if} +
  • +{/snippet} + {#if failed.length}
    - (collapsed = !collapsed)} class="w-full px-6 pt-2 pb-1"> - {plural(failed.length, 'node')} failed - {#if skipped}· {skipped} skipped because of {failed.length === 1 ? 'it' : 'them'}{/if} - - {#if !collapsed} -
      - {#each failed as n (`${n.runId}/${n.nodeKey}`)} - {@const key = `${n.runId}/${n.nodeKey}`} - {@const loaded = read(key)} - {@const where = place(n, key)} - {@const detail = n.errorDetail ?? loaded?.message ?? null} -
    • -
      - {#if app.client.supports('listRunStatements')}{:else}{n.nodeKey}{/if} - {#if n.runId !== view.run?.id}in {n.jobKey ?? shortRunId(n.runId)}{/if} - {n.errorMessage ?? loaded?.message?.split('\n')[0] ?? (n.errorCode ? `Failed with ${n.errorCode}` : 'Failed')} - {#if where} - {where} - - {/if} - {#if n.errorDetail || readable} - - {/if} -
      - {#if open.has(key)} - {@const got = errors[key]} - {#if detail} -
      {detail}
      - {:else if got && 'failure' in got} -

      {got.failure}

      - {:else if got} -

      No error text was recorded for this node.

      - {:else if !n.errorDetail} -

      Loading the error…

      - {/if} - {#if n.errorCode && detail}

      Error code {n.errorCode}

      {/if} - {/if} -
    • - {/each} -
    + {#if single} +
      {@render line(failed[0])}
    + {:else} + + + {#if listOpen} +
      + {#each failed as n (`${n.runId}/${n.nodeKey}`)}{@render line(n)}{/each} +
    + {/if} {/if}
    {/if} @@ -104,32 +102,56 @@ diff --git a/ui/src/routes/runs/[id]/log-tab.svelte b/ui/src/routes/runs/[id]/log-tab.svelte index 68dd70a8e9..599e14af6b 100644 --- a/ui/src/routes/runs/[id]/log-tab.svelte +++ b/ui/src/routes/runs/[id]/log-tab.svelte @@ -7,13 +7,20 @@ import { to } from '$lib/paths'; import DisclosureButton from '$lib/components/disclosure-button.svelte'; import DownloadIcon from '@lucide/svelte/icons/download'; - import SearchIcon from '@lucide/svelte/icons/search'; - import type { RunEventLevel } from '$lib/api'; + import type { RunEventLevel, RunStatement } from '$lib/api'; + import CheckList from './check-list.svelte'; + import QueryPanel from './query-panel.svelte'; + import TracebackPanel from './traceback-panel.svelte'; import { formatStamp } from '$lib/format/time'; - import { clockTime, nodeLabel, shortRunId } from '$lib/operate/labels'; - import type { EventCategory } from './types'; - import { EVENT_CATEGORIES, type LogEntry } from './utils'; + import { nodeLabel, shortRunId } from '$lib/operate/labels'; + import type { LogEntry } from './utils'; + import { CHECK_FAILED_CODE, fullStamp, tracebackOf } from './utils'; import SegmentedFilter from '$lib/components/list/segmented-filter.svelte'; + import * as DropdownMenu from '$lib/components/ui/dropdown-menu'; + import LogFilter, { type FilterOption } from './log-filter.svelte'; + import ChevronDownIcon from '@lucide/svelte/icons/chevron-down'; + import { cn } from '$lib/utils'; + import { buttonVariants } from '$lib/components/ui/button/button.svelte'; let { entries, @@ -21,6 +28,12 @@ runId, filteredBy, printed = $bindable(false), + memberOf = () => null, + memory, + statements = [], + onquery, + onframe, + onnode, onstatement }: { entries: LogEntry[]; @@ -29,6 +42,18 @@ filteredBy: string[]; /** Whether what the run printed is shown; a failing run's last printed block always is. */ printed?: boolean; + /** A node name clicked: the log shows only that node. */ + onnode?: (nodeKey: string) => void; + /** The page's memory, so Back restores the log as it was. */ + memory?: Record; + /** A frame in a node's own code: show that line in the drawer. */ + onframe?: (nodeKey: string, line: number) => void; + /** The run's statements, for a check's query ID and duration. */ + statements?: readonly RunStatement[]; + /** Shows a check's query in the Statements tab. */ + onquery?: (statementId: string, nodeKey: string) => void; + /** A group run's member job, by member run, for the quiet tag beside a node. */ + memberOf?: (runId: string) => string | null; /** Opens a query's statement, with its SQL. */ onstatement?: (nodeKey: string) => void; } = $props(); @@ -41,30 +66,90 @@ { value: 'info', label: 'Info' }, { value: 'debug', label: 'Debug' } ]; - let level = $state('all'); - let category = $state('all'); - let query = $state(''); + // One source of truth: the filter text. The Levels and Kinds menus and the counts only write + // `level:` and `kind:` into it. + // Back to the page restores the log as it was: its filter, stream and open rows. + const mem = (key: string, fallback: T): T => (memory && key in memory ? (memory[key] as T) : fallback); + // svelte-ignore state_referenced_locally + let query = $state(mem('logQuery', '')); // Long printed blocks fold to their first lines. const FOLD = 4; - let open = $state>(new Set()); + // svelte-ignore state_referenced_locally + let open = $state>(new Set(mem('logFolded', []))); // Nodes whose queries are listed under their outcome row. - let expanded = $state>(new Set()); + // svelte-ignore state_referenced_locally + let expanded = $state>(new Set(mem('logQueries', []))); - // Printed output has its own switch; a kind chip shows only when the log has that kind. - const present = $derived(EVENT_CATEGORIES.filter((c) => c.value !== 'output' && entries.some((e) => e.category === c.value))); + // Events | Output: the run's events, or what sqb and the nodes printed (`printed`). const hasOutput = $derived(entries.some((e) => e.category === 'output')); - const hidden = $derived(entries.filter((e) => e.category === 'output' && !e.pinned).length); - const kindShown = (e: LogEntry) => (e.category === 'output' ? printed || e.pinned : category === 'all' || e.category === category); - const levelShown = (e: LogEntry) => level === 'all' || e.level === level; - const q = $derived(query.trim().toLowerCase()); - const matches = (e: LogEntry) => !q || [e.nodeKey ?? '', e.text, e.title, ...e.queries.map((x) => x.text)].join(' ').toLowerCase().includes(q); - const byCategory = $derived(entries.filter(kindShown)); - const byLevel = $derived(entries.filter((e) => levelShown(e) && e.category !== 'output')); - const shown = $derived(entries.filter((e) => levelShown(e) && kindShown(e) && matches(e))); - const levelCounts = $derived(countBy(byCategory, (e) => e.level)); - const categoryCounts = $derived(countBy(byLevel, (e) => e.category)); - const levelOptions = $derived(LEVELS.map((l) => ({ ...l, count: l.value === 'all' ? byCategory.length : (levelCounts.get(l.value) ?? 0) }))); - const kindOptions = $derived([{ value: 'all' as const, label: 'All kinds', count: byLevel.length }, ...present.map((c) => ({ value: c.value, label: c.label, count: categoryCounts.get(c.value) ?? 0 }))]); + const inMode = (e: LogEntry) => (printed ? e.category === 'output' : e.category !== 'output'); + const modeEntries = $derived(entries.filter(inMode)); + // svelte-ignore state_referenced_locally + let stream = $state<'all' | 'stdout' | 'stderr'>(mem('logStream', 'all')); + const kindOf = (e: LogEntry) => e.tag?.text.replace(/ /g, '-') ?? null; + type Term = { key: string; value: string }; + const terms = $derived( + query + .trim() + .split(/\s+/) + .filter(Boolean) + .map((t): Term => { + const m = t.match(/^(node|kind|level|job|stream):(.*)$/i); + return m ? { key: m[1].toLowerCase(), value: m[2].toLowerCase() } : { key: 'text', value: t.toLowerCase() }; + }) + ); + const holds = (e: LogEntry, t: Term) => { + if (!t.value) return true; + if (t.key === 'node') return !!e.nodeKey && nodeLabel(e.nodeKey).toLowerCase() === t.value; + if (t.key === 'kind') return kindOf(e) === t.value; + if (t.key === 'level') return e.level === (t.value === 'warning' ? 'warn' : t.value); + if (t.key === 'job') return memberOf(e.runId)?.toLowerCase() === t.value; + if (t.key === 'stream') return e.stream === t.value; + return [e.nodeKey ?? '', e.text, e.title, ...e.queries.map((x) => x.text)].join(' ').toLowerCase().includes(t.value); + }; + const matchesExcept = (e: LogEntry, skip: string | null) => terms.every((t) => t.key === skip || holds(e, t)) && (!printed || stream === 'all' || e.stream === stream); + const shown = $derived(modeEntries.filter((e) => matchesExcept(e, null))); + const termValue = (key: string) => terms.find((t) => t.key === key && t.value)?.value ?? null; + const level = $derived((termValue('level') === 'warning' ? 'warn' : termValue('level')) ?? 'all'); + const kind = $derived(termValue('kind') ?? 'all'); + /** Writes `key:value` into the filter text, in place of any earlier one; null takes it out. */ + function setTerm(key: string, value: string | null) { + const kept = query.split(/\s+/).filter((t) => t && !t.toLowerCase().startsWith(`${key}:`)); + query = [...kept, ...(value ? [`${key}:${value}`] : [])].join(' ') + (kept.length || value ? ' ' : ''); + } + const uniq = (xs: (string | null | undefined)[]) => [...new Set(xs.filter((x): x is string => !!x))].sort(); + const kindValues = $derived(printed ? [] : uniq(modeEntries.map(kindOf))); + const filterOptions = $derived([ + { prefix: 'node', hint: 'a node', values: uniq(entries.map((e) => (e.nodeKey ? nodeLabel(e.nodeKey) : null))) }, + { prefix: 'kind', hint: 'built, merged, failed, check, log…', values: kindValues }, + { prefix: 'level', hint: 'error, warn, info', values: uniq(modeEntries.map((e) => e.level)) }, + { prefix: 'job', hint: 'a member job', values: grouped ? uniq(entries.map((e) => memberOf(e.runId))) : [] }, + { prefix: 'stream', hint: 'stdout or stderr', values: printed ? uniq(entries.map((e) => e.stream)) : [] } + ]); + // Counts for each menu choice: what the rest of the filter leaves, by level or by kind. + const levelCounts = $derived(countBy(modeEntries.filter((e) => matchesExcept(e, 'level')), (e) => e.level)); + const kindCounts = $derived(countBy(modeEntries.filter((e) => matchesExcept(e, 'kind')), (e) => kindOf(e) ?? '')); + // A count shows only when it matters: errors and warnings in what the switch shows, none when zero. + const errors = $derived(levelCounts.get('error') ?? 0); + const warnings = $derived(levelCounts.get('warn') ?? 0); + const levelText = $derived(LEVELS.find((l) => l.value === level)?.label ?? 'Levels'); + const levelOptions = $derived(LEVELS.map((l) => ({ ...l, count: l.value === 'all' ? [...levelCounts.values()].reduce((a, b) => a + b, 0) : (levelCounts.get(l.value) ?? 0) }))); + const kindOptions = $derived([{ value: 'all', label: 'All kinds', count: [...kindCounts.values()].reduce((a, b) => a + b, 0) }, ...kindValues.map((k) => ({ value: k, label: k, count: kindCounts.get(k) ?? 0 }))]); + // Rows whose structured details are open in place; long text stays folded until "show more". + // svelte-ignore state_referenced_locally + let detailOpen = $state>(new Set(mem('logDetails', []))); + // svelte-ignore state_referenced_locally + let longOpen = $state>(new Set(mem('logLong', []))); + $effect(() => { + if (memory) Object.assign(memory, { logQuery: query, logStream: stream, logFolded: [...open], logQueries: [...expanded], logDetails: [...detailOpen], logLong: [...longOpen] }); + }); + + /** A node line's queries (its build statements, not its checks'), or a query row's own statement. */ + function queriesOf(e: LogEntry): RunStatement[] { + if (e.statementId && e.category === 'queries') return statements.filter((q) => q.id === e.statementId); + if (!e.node) return []; + return statements.filter((q) => q.nodeKey === e.node!.nodeKey && q.runId === e.runId && q.kind !== 'audit'); + } function toggle(set: Set, value: T): Set { const next = new Set(set); @@ -84,152 +169,337 @@ URL.revokeObjectURL(url); } const logColumns = $derived([ - { id: 'time', label: 'Time', width: '110px' }, - ...(grouped ? [{ id: 'run', label: 'Job run', width: '100px' }] : []), - { id: 'node', label: 'Node', width: '220px' }, + // Full timestamps, never cropped. + { id: 'time', label: 'Time', width: '206px' }, + // A group run's member job is a quiet tag beside the node, not a column of its own. + { id: 'node', label: 'Node', width: grouped ? '320px' : '230px' }, + ...(printed ? [] : [{ id: 'tag', label: '', width: '78px' }]), { id: 'what', label: 'What happened', minWidth: 300, truncate: false } ]); +
    - - {#if present.length > 1}{/if} {#if hasOutput} - + (printed = v === 'output')} + options={[ + { value: 'events', label: 'Events' }, + { value: 'output', label: 'Output' } + ]} + /> + {/if} + {#if printed} + {/if} - - + + + {level === 'all' ? 'Levels' : levelText} + + setTerm('level', v === 'all' ? null : v)}> + {#each levelOptions as l (l.value)}{l.label}{l.count}{/each} + + + + {#if !printed && kindValues.length > 1} + + {kind === 'all' ? 'Kinds' : kind} + + setTerm('kind', v === 'all' ? null : v)}> + {#each kindOptions as k (k.value)}{k.label}{k.count}{/each} + + + + {/if} + {#if errors}{/if} + {#if warnings}{/if} + +
    e.id} empty={entries.length ? 'Nothing in the log matches these filters.' : 'Nothing logged yet.'}> {#snippet row(e)} - - {clockTime(e.at)} - {#if grouped}{shortRunId(e.runId)}{/if} - {e.nodeKey ? nodeLabel(e.nodeKey) : (e.stream ?? 'run')} - - {#if e.stream} + + {fullStamp(e.at)} + + + {#if e.nodeKey && onnode} { + ev.preventDefault(); + onnode(e.nodeKey!); + }}>{nodeLabel(e.nodeKey)}{:else}{e.nodeKey ? nodeLabel(e.nodeKey) : 'run'}{/if} + {#if grouped && memberOf(e.runId)}{memberOf(e.runId)}{/if} + + {#if !printed}{#if e.tag}{e.tag.text}{/if}{/if} + e.details?.length && (detailOpen = toggle(detailOpen, e.id))}> + {#if e.omitted && e.nodeKey} + + +{e.omitted.toLocaleString('en-GB')} lines · open in viewer → + {:else if e.stream} {@const lines = e.text.split('\n')} {open.has(e.id) || lines.length <= FOLD ? e.text : lines.slice(0, FOLD).join('\n')} {#if lines.length > FOLD}{/if} {:else} - {e.text} - {#if e.queries.length} - (expanded = toggle(expanded, e.id))} class="ml-2 gap-0.5 text-[11.5px]">{plural(e.queries.length, 'query', 'queries')} + {#if e.category === 'nodes' && e.id.startsWith('node-')} + + {e.text.slice(0, 1)}{e.text.slice(1)} + {:else} + {e.text} + {/if} + {#if e.details?.length}{/if} + {#if queriesOf(e).length} + + { + ev.stopPropagation(); + expanded = toggle(expanded, e.id); + }} + class="ml-2 gap-0.5 text-[11.5px]">{plural(queriesOf(e).length, 'query', 'queries')} {/if} {/if} - {#if e.statementId && e.nodeKey && onstatement && e.category === 'queries'} - + {#if e.statementId && e.category === 'queries' && queriesOf(e).length} + {/if} - {#if expanded.has(e.id)} - {#each e.queries as x (x.id)} - - {clockTime(x.at)} - {#if grouped}{/if} - - - {x.text} - {#if x.statementId && x.nodeKey && onstatement} - - {/if} - - - {/each} + {#if detailOpen.has(e.id) && e.details?.length} + + + + +
    + {#each e.details as [k, v], i (i)}
    {k}
    {v}
    {/each} +
    + {#if e.checks?.length} +
    onquery(id, e.nodeKey!) : undefined} />
    + {/if} + {#if e.node && tracebackOf(e.long)} + +
    onframe(e.node!.nodeKey, line) : undefined} />
    + {:else if e.node?.status === 'failed' && queriesOf(e).some((q) => q.status === 'failed')} + + {#each queriesOf(e).filter((q) => q.status === 'failed') as q (q.id)} +
    onquery(q.id, q.nodeKey) : undefined} />
    + {/each} + {:else if e.long && e.node?.errorCode !== CHECK_FAILED_CODE} + {@const lines = e.long.split('\n')} +
    {longOpen.has(e.id) ? e.long : lines.slice(0, 3).join('\n')}
    + {#if lines.length > 3}{/if} + {/if} + + + {/if} + {#if expanded.has(e.id) && queriesOf(e).length} + + + + {#each queriesOf(e) as q (q.id)} +
    onquery(q.id, q.nodeKey) : undefined} />
    + {/each} + + {/if} {/snippet}
    diff --git a/ui/src/routes/runs/[id]/node-panel.svelte b/ui/src/routes/runs/[id]/node-panel.svelte deleted file mode 100644 index c44e27ba3c..0000000000 --- a/ui/src/routes/runs/[id]/node-panel.svelte +++ /dev/null @@ -1,180 +0,0 @@ - - -
    - {#each groups as g (g.key)} -
    - {#if summary} - - - {:else} - - - {/if} - {#if open(g.key)} -
      - {#each g.nodes as n (`${n.runId}/${n.nodeKey}`)} -
    • - - - {#if n.skippedBecauseOf} - {@const why = n.skippedBecauseOf} -
      - skipped: - {#if why.runId === ownRun || view.nodes.some((x) => x.nodeKey === why.nodeKey)} - - {:else} - {why.nodeKey} - {/if} - failed{#if why.runId !== n.runId} in {why.jobKey ?? shortRunId(why.runId)}{/if} -
      - {:else if n.status !== 'pending' && notRunReason(n, view.active)} -
      {notRunReason(n, view.active)}
      - {/if} -
    • - {/each} -
    - {/if} -
    - {:else} -

    No nodes yet.

    - {/each} -
    - - diff --git a/ui/src/routes/runs/[id]/output/[node]/+page.svelte b/ui/src/routes/runs/[id]/output/[node]/+page.svelte new file mode 100644 index 0000000000..2ac4f0919f --- /dev/null +++ b/ui/src/routes/runs/[id]/output/[node]/+page.svelte @@ -0,0 +1,412 @@ + + + + +
    +
    + +

    {nodeLabel(nodeKey)} output

    + {#if index} +
    + {fmt(index.total)} lines·{mb(index.bytes)}· + {fmt(index.stdout)} stdout, {fmt(index.stderr)} stderr + {#if errors}·{errors} errors{/if} + {#if warnings}·{warnings} warnings{/if} + {#if index.live}·still writing{/if} +
    + {/if} +
    + + {#if !supported} +

    This server doesn't serve paged output yet.

    + {:else} +
    + ((stream = v), load(1))} + options={[ + { value: 'all', label: 'All' }, + { value: 'stdout', label: 'stdout' }, + { value: 'stderr', label: 'stderr' } + ]} + /> + + + + + +
    (e.preventDefault(), jumpToLine())}> + +
    + +
    + {#if view}
    Lines {fmt(view.from)}–{fmt(Math.max(view.from, view.to - 1))} of {fmt(total)}{#if loading} · loading…{/if}
    {/if} + + + {#if failed} +

    Couldn't read this output: {failed}

    + {:else if view} +
    + {#each view.rows as r (r.kind === 'line' ? r.line.n : `s${r.from}`)} + {#if r.kind === 'line'} +
    + {fmt(r.line.n)} +
    {#each parts(r.line.text) as p, i (i)}{#if p.hit}{p.t}{:else}{p.t}{/if}{/each}
    +
    + {:else} + + + {/if} + {/each} +
    + {:else if loading} +

    Reading the output…

    + {/if} +
    + {/if} +
    + + diff --git a/ui/src/routes/runs/[id]/query-panel.svelte b/ui/src/routes/runs/[id]/query-panel.svelte new file mode 100644 index 0000000000..6f06ee6c06 --- /dev/null +++ b/ui/src/routes/runs/[id]/query-panel.svelte @@ -0,0 +1,120 @@ + + +
    +
    + {OUTCOME[st.status]} + {st.kind} + {#if rows}{rows}{/if} + {took} + {#if st.queryId} + Query {st.queryId}{#if queryUrl}open in warehouse ↗{/if} + {/if} + {#if onstatements}{/if} +
    + {#if st.error} + +
    {fullError || errorLines.length <= 8 ? st.error : errorLines.slice(0, 8).join('\n')}
    + {#if errorLines.length > 8}{/if} + {/if} + {#if sql.state === 'ok' && sql.sql} +
    {sql.sql}
    + {:else if sql.state === 'ok'}

    The SQL wasn't recorded.

    + {:else if sql.state === 'error'}

    Couldn't load the SQL: {sql.message}

    + {:else}

    Loading the SQL…

    {/if} +
    + + diff --git a/ui/src/routes/runs/[id]/related-runs.svelte b/ui/src/routes/runs/[id]/related-runs.svelte index f7d2871dde..88955f5985 100644 --- a/ui/src/routes/runs/[id]/related-runs.svelte +++ b/ui/src/routes/runs/[id]/related-runs.svelte @@ -10,7 +10,8 @@ import { app } from '$lib/state/app.svelte'; import { runStatusLabel, runStatusTone } from '$lib/status'; import type { RunDetailState } from './state.svelte'; - import { attemptLabel } from './utils'; + import { attemptLabel, costSummary } from './utils'; + import Button from '$lib/components/ui/button/button.svelte'; let { view }: { view: RunDetailState } = $props(); @@ -36,9 +37,28 @@ {#if d} - {#if related.length} -
    - Related + +{#snippet selection(keys: string[])} + {#if keys.length > 12} +
    {keys.length} nodes{keys.join(' ')}
    + {:else} + {keys.join(' ') || '—'} + {/if} +{/snippet} + +{#if view.showDetails} + {@const p = d.provenance} +
    +
    + + {#if view.progress.total}
    Nodes
    {view.progress.done}/{view.progress.total} finished
    {/if} + {#if view.cost && view.cost.status !== 'none'} +
    Cost
    + {/if} + {#if related.length} +
    +
    Related runs
    +
      {#each related as r (`${r.role}-${r.run.id}`)}
    • @@ -51,26 +71,14 @@ {@const attempt = attemptLabel(r.run, d.children)} {#if attempt}{attempt}{/if} {/if} - {runStatusLabel[r.run.status].toLowerCase()} + {r.run.status === 'skipped' && r.run.parentRunId && !r.run.startedAt ? 'not started' : runStatusLabel[r.run.status].toLowerCase()}
    • {/each}
    -
    - {/if} - -{#snippet selection(keys: string[])} - {#if keys.length > 12} -
    {keys.length} nodes{keys.join(' ')}
    - {:else} - {keys.join(' ') || '—'} - {/if} -{/snippet} - -{#if view.showDetails} - {@const p = d.provenance} -
    -
    + +
    + {/if} {#if p}
    Project version
    Version {p.snapshotGeneration}{#if p.gitRevision} · commit {p.gitRevision}{/if}{#if p.gitDirty} · dirty{/if} · snapshot {p.snapshotId}
    {#if p.command}
    Command
    {p.command}
    {/if} @@ -116,19 +124,6 @@ {/if} diff --git a/ui/src/routes/runs/[id]/run-gantt.svelte b/ui/src/routes/runs/[id]/run-gantt.svelte index 8a423ef12a..a25ee28e36 100644 --- a/ui/src/routes/runs/[id]/run-gantt.svelte +++ b/ui/src/routes/runs/[id]/run-gantt.svelte @@ -1,5 +1,4 @@
    @@ -31,64 +51,23 @@ {#if run} +

    {#if run.jobKey}{run.jobKey}{:else}ad hoc: {what}{/if}

    - - {#if retried}· {retried} retried{/if} - - {runKindLabel[run.kind].toLowerCase()} - {#if run.narrowing} - part · {narrowingText(run.narrowing)} - {/if} - {#if run.window} - window · {run.window.start} → {run.window.end} - {/if} - {#if run.triggerId} - {runOriginLabel[run.origin].toLowerCase()}{#if run.triggerName}: {run.triggerName}{/if} - {:else if run.rerunOfRunId} - rerun of {shortRunId(run.rerunOfRunId)} - {:else} - {runOriginLabel[run.origin].toLowerCase()} - {/if} + + + {#each facts as f, i (i)} + {#if i}{' · '}{/if} + {#if f.href}{f.text}{:else}{f.text}{/if} + {/each} +
    -
    - {#if run.startedAt} - Started {formatStamp(run.startedAt)} ({formatAgo(run.startedAt, app.now)}) - · - {view.active ? 'running for ' : 'took '}{formatDuration(run.startedAt, run.endedAt, app.now)} - {#if view.cost && view.cost.status !== 'none'} - {@const summary = costSummary(view.cost)} - · - - {/if} - {:else} - Queued {formatAgo(run.queuedAt, app.now)} - {/if} - · - by {run.requestedBy.displayName} - {#if view.progress.total} - - - {view.progress.done}/{view.progress.total} nodes - - {/if} - {#if view.detail?.provenance} - {@const p = view.detail.provenance} - · - version {p.snapshotGeneration} - {/if} - - {#if run.jobKey} - - Plan it now - {/if} +
    + +
    - {#if view.detail?.provenance?.command} - {@const command = view.detail.provenance.command} -
    $ {command}
    - {/if} {:else if view.detailRes.error}

    Couldn't load this run: {view.detailRes.error}

    {:else if view.detailRes.data === null} @@ -110,32 +89,18 @@ {/if} -
    {/if}
    {#if view.actionError}{/if} diff --git a/ui/src/routes/runs/[id]/run-lineage.svelte b/ui/src/routes/runs/[id]/run-lineage.svelte new file mode 100644 index 0000000000..e96ecf00a3 --- /dev/null +++ b/ui/src/routes/runs/[id]/run-lineage.svelte @@ -0,0 +1,148 @@ + + +{#if isGroup} +
    + + {#if groupJob.data?.groupMembers && memberNodes.data && catalog.data} + + + {:else} +
    Loading the group's lineage…
    + {/if} +
    +{:else} +
    + + +
    +{/if} + + diff --git a/ui/src/routes/runs/[id]/run-summary.svelte b/ui/src/routes/runs/[id]/run-summary.svelte new file mode 100644 index 0000000000..a28cdac6c6 --- /dev/null +++ b/ui/src/routes/runs/[id]/run-summary.svelte @@ -0,0 +1,84 @@ + + +
    + {#each figs as f, i (f.key)} + + {#if i}{' · '}{/if} + + { + ev.preventDefault(); + view.focusGroup(f.key, f.text.replace(/^\d+ /, '')); + }} + title="Show only these on the timeline and in the log">{f.text}{#if f.note}{` ${f.note}`}{/if} + {:else} + {view.active ? 'Starting…' : 'No nodes ran.'} + {/each} +
    + + diff --git a/ui/src/routes/runs/[id]/run-tabs.svelte b/ui/src/routes/runs/[id]/run-tabs.svelte index bf3c77ffc4..4d89ecf5f8 100644 --- a/ui/src/routes/runs/[id]/run-tabs.svelte +++ b/ui/src/routes/runs/[id]/run-tabs.svelte @@ -10,26 +10,103 @@ import CostTab from './cost-tab.svelte'; import type { BottomTab } from './types'; import { bottomTabs, logEntries } from './utils'; + import { tick } from 'svelte'; + import { plural } from '$lib/format/plural'; + import { skipCause } from './utils'; let { view }: { view: RunDetailState } = $props(); - const sel = $derived(new Set(view.selected)); + // The log follows a summary figure or a node picked in the log, else the selection (until "Show all"). + // Back to the page restores the log as it was: these too, and where it was scrolled. + // svelte-ignore state_referenced_locally + const mem = view.memory; + let ignoreSelection = $state((mem.ignoreSelection as boolean) ?? false); + let lastSelection = (mem.lastSelection as string) ?? ''; + $effect(() => { + const key = view.selected.join(','); + if (key !== lastSelection) { + lastSelection = key; + ignoreSelection = false; + } + Object.assign(mem, { ignoreSelection, lastSelection }); + }); + const filterKeys = $derived(view.focus ? view.focus.keys : ignoreSelection ? [] : view.selected); + const sel = $derived(new Set(filterKeys)); const filtering = $derived(sel.size > 0); - const entries = $derived(logEntries(view.eventsRes.data ?? [], view.outputRes.data ?? [])); + // One line per node outcome, with its checks folded in; `app.now` keeps a building node's line current. + const edges = $derived(view.detail?.edges ?? []); + const entries = $derived(logEntries(view.events, view.outputRes.data ?? [], { nodes: view.nodes, skipCause: (n) => skipCause(n, view.nodes, edges), now: app.now })); const statements = $derived(filtering ? view.statements.filter((s) => sel.has(s.nodeKey)) : view.statements); - // Printed lines name no node, so a node filter keeps the lines that mention one of the selected nodes. - const shownEntries = $derived(filtering ? entries.filter((e) => (e.nodeKey ? sel.has(e.nodeKey) : view.selected.some((k) => e.text.includes(k)))) : entries); + // Printed lines carry their node when sqb printed them for one; others are kept when they mention it. + const shownEntries = $derived(filtering ? entries.filter((e) => (e.nodeKey ? sel.has(e.nodeKey) : filterKeys.some((k) => e.text.includes(k)))) : entries); const grouped = $derived((view.detail?.children.length ?? 0) > 0); // Kept here so the choice survives switching tabs, and the Log count matches the rows shown. - let printed = $state(false); - const logCount = $derived(shownEntries.filter((e) => printed || e.category !== 'output' || e.pinned).length); + // Events | Output: the log opens on its events, one line per node; Output is what sqb printed. + let printed = $state((mem.printed as boolean) ?? false); + $effect(() => { + mem.printed = printed; + }); + const logCount = $derived(shownEntries.filter((e) => (printed ? e.category === 'output' : e.category !== 'output')).length); const TABS = $derived(bottomTabs(app.client, (c) => app.can(c), !!view.cost && view.cost.status !== 'none')); $effect(() => { if (TABS.length && !TABS.some((t) => t.value === view.tab)) view.tab = TABS[0].value; }); - const count = (t: BottomTab) => (t === 'statements' ? statements.length : t === 'cost' ? (view.cost?.resources.length ?? 0) : logCount); - const chipText = $derived(view.selected.length === 1 ? view.selected[0] : `${view.selected.length} nodes`); + const count = (t: BottomTab) => (t === 'statements' ? statements.length : t === 'cost' ? (view.cost?.resources.filter((r) => !filtering || sel.has(r.nodeKey)).length ?? 0) : logCount); + const chipText = $derived(view.focus ? view.focus.label : filterKeys.length === 1 ? filterKeys[0] : `${filterKeys.length} selected nodes`); + function showAll() { + if (view.focus) view.clearFocus(); + else ignoreSelection = true; + } + + // ---- the log follows new lines while it is at the bottom ---- + let scroller = $state(); + // A running run's log opens at its newest line; a finished run's at its first. + let atBottom = $state(untrackActive()); + function untrackActive() { + return view.active; + } + let seen = $state(0); + const fresh = $derived(Math.max(0, logCount - seen)); + // Where the log was scrolled, put back once its rows are in. + let restored = !('logScroll' in mem); + $effect(() => { + if (restored || !scroller || !logCount) return; + restored = true; + const top = mem.logScroll as number; + void tick().then(() => scroller && (scroller.scrollTop = top)); + }); + function onscroll() { + if (!scroller) return; + if (restored) mem.logScroll = scroller.scrollTop; + atBottom = scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 24; + if (atBottom) seen = logCount; + } + async function toBottom() { + await tick(); + if (!scroller) return; + scroller.scrollTop = scroller.scrollHeight; + atBottom = true; + seen = logCount; + } + // A new filter or the printed-output switch changes what is shown, not what is new. + let shownKey = ''; + $effect(() => { + const key = `${filterKeys.join(',')}|${printed}`; + if (key === shownKey) return; + shownKey = key; + seen = untrackCount(); + }); + function untrackCount() { + return logCount; + } + $effect(() => { + void logCount; + if (view.tab !== 'log') return; + // Only a run still going adds lines; a finished run's log arrives in parts, which are not new. + if (!view.active) seen = logCount; + if (atBottom) void toBottom(); + });
    @@ -40,27 +117,52 @@ /> {#if filtering} - Filtered: {chipText} - + Filtered to {chipText} + {/if}
    - +
    + {#if view.tab === 'statements'} - + {:else if view.tab === 'cost'} {#if view.cost} - view.focusNode(key, 'cost')} /> + view.focusNode(key, 'cost')} /> {:else if view.costRes.error}

    Couldn't load this run's cost: {view.costRes.error}

    {/if} {:else} - view.focusNode(key, 'statements') : undefined} /> + view.showStatement(id, key)} onframe={(key, line) => view.openCode(key, line)} memberOf={(id) => view.detail?.children.find((c) => c.id === id)?.jobKey ?? null} bind:printed runId={view.run?.id ?? ''} filteredBy={filterKeys} onnode={(key) => view.focusNode(key, 'log')} onstatement={app.client.supports('listRunStatements') ? (key) => view.focusNode(key, 'statements') : undefined} /> {/if}
    +{#if view.tab === 'log' && !atBottom && fresh > 0} + + +{/if} +
    diff --git a/ui/src/routes/runs/[id]/types.ts b/ui/src/routes/runs/[id]/types.ts index b2402b5a36..c831d8940e 100644 --- a/ui/src/routes/runs/[id]/types.ts +++ b/ui/src/routes/runs/[id]/types.ts @@ -3,7 +3,7 @@ import type { RunNode, RunNodeStatus } from '$lib/api'; export type BottomTab = 'log' | 'statements' | 'cost'; /** The node panel's groups, in display order. */ -export type NodeGroupKey = 'running' | 'waiting' | 'failed' | 'skipped' | 'succeeded' | 'not_run'; +export type NodeGroupKey = 'running' | 'waiting' | 'failed' | 'skipped' | 'succeeded' | 'not_run' | 'warned'; export type NodeGroup = { key: NodeGroupKey; label: string; tone: string; statuses: RunNodeStatus[]; nodes: RunNode[] }; /** Event categories for the Events tab filter. */ diff --git a/ui/src/routes/runs/[id]/utils/banners.ts b/ui/src/routes/runs/[id]/utils/banners.ts index 463d8627e3..012baf8b49 100644 --- a/ui/src/routes/runs/[id]/utils/banners.ts +++ b/ui/src/routes/runs/[id]/utils/banners.ts @@ -50,7 +50,7 @@ export function bannersFor(detail: RunDetail, now: number, cause: string | null key: 'lost-final', tone: 'error', title: `Lost contact — marked failed after ${short(live?.presumedFailedAfterSeconds ?? 600)} of silence.`, - body: [{ text: 'Rerunning is safe: the run has been stopped. Use Rerun from failure to finish the nodes it didn’t complete.' }], + body: [{ text: 'Rerunning is safe: the run has been stopped. To finish the nodes it didn’t complete, pick Failed + downstream and plan them.' }], detail: run.statusReason ?? undefined }); } diff --git a/ui/src/routes/runs/[id]/utils/checks.ts b/ui/src/routes/runs/[id]/utils/checks.ts new file mode 100644 index 0000000000..3627b1441e --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/checks.ts @@ -0,0 +1,78 @@ +// A node's checks from their results in the run, problems first, and the short form a node's one log line uses. Pure. + +import type { RunEvent } from '$lib/api'; + +export type CheckOutcome = 'failed' | 'warned' | 'passed' | 'skipped'; +export type CheckResult = { + id: string; + /** As declared, such as `not_null(payment_id)`. */ + name: string; + outcome: CheckOutcome; + /** Rows it found, and what they are, such as `14` and `duplicate rows`; null when it passed. */ + count: number | null; + noun: string | null; + /** The check's own query, for its SQL, query ID and failing rows. */ + statementId: string | null; + /** The check's ID and this result's, for the rows it found. */ + bindingKey: string | null; + resultId: string | null; +}; + +const RANK: Record = { failed: 0, warned: 1, passed: 2, skipped: 3 }; + +/** A node's checks from its `audit_completed` events, problems first (failed, then warned), then passed and skipped. */ +export function checksOf(events: readonly RunEvent[]): CheckResult[] { + return events + .filter((e) => e.type === 'audit_completed') + .map((e): CheckResult => { + const check = e.check ?? { name: e.message || 'check', outcome: e.level === 'error' ? 'failed' : e.level === 'warn' ? 'warned' : 'passed', rows: null, bindingKey: null, resultId: null }; + const problem = check.outcome === 'failed' || check.outcome === 'warned'; + return { + id: e.id, + name: check.name, + outcome: check.outcome, + count: problem ? check.rows : null, + noun: problem ? (check.name.startsWith('unique') ? 'duplicate rows' : 'failing rows') : null, + statementId: e.statementId, + bindingKey: check.bindingKey, + resultId: check.resultId + }; + }) + .sort((a, b) => RANK[a.outcome] - RANK[b.outcome]); +} + +/** The worst outcome among the checks, or null without any. */ +export function worstCheck(checks: readonly CheckResult[]): CheckOutcome | null { + return checks.length ? checks.reduce((w, c) => (RANK[c.outcome] < RANK[w] ? c.outcome : w), 'passed' as CheckOutcome) : null; +} + +const rows = (c: CheckResult) => `${(c.count ?? 0).toLocaleString('en-GB')} ${c.count === 1 ? 'row' : 'rows'}`; + +/** + * The checks on a node's one line: all passing is counted ("5 checks passed"); one or two problems are + * named ("not_null(payment_id) warned: 2 rows", "2 checks warned (a, b)"); more are counted + * ("1 failed · 3 warned"); passing checks beside problems are only counted ("4 passed"). + */ +export function checksText(checks: readonly CheckResult[]): string | null { + if (!checks.length) return null; + const failed = checks.filter((c) => c.outcome === 'failed'); + const warned = checks.filter((c) => c.outcome === 'warned'); + const passed = checks.filter((c) => c.outcome === 'passed').length; + const problems = failed.length + warned.length; + if (!problems) return `${passed} ${passed === 1 ? 'check' : 'checks'} passed`; + const parts: string[] = []; + if (problems === 1) { + const c = failed[0] ?? warned[0]; + parts.push(`${c.name} ${c.outcome}: ${rows(c)}`); + } else if (problems === 2 && (failed.length === 2 || warned.length === 2)) { + const same = failed.length === 2 ? failed : warned; + parts.push(`2 checks ${same[0].outcome} (${same.map((c) => c.name).join(', ')})`); + } else if (problems === 2) { + parts.push(`${failed[0].name} failed: ${rows(failed[0])}`, `${warned[0].name} warned: ${rows(warned[0])}`); + } else { + if (failed.length) parts.push(`${failed.length} failed`); + if (warned.length) parts.push(`${warned.length} warned`); + } + if (passed) parts.push(`${passed} passed`); + return parts.join(' · '); +} diff --git a/ui/src/routes/runs/[id]/utils/events.ts b/ui/src/routes/runs/[id]/utils/events.ts index 64663d78e0..989e0ddfe6 100644 --- a/ui/src/routes/runs/[id]/utils/events.ts +++ b/ui/src/routes/runs/[id]/utils/events.ts @@ -1,20 +1,22 @@ // Plain one-line summaries of run events; the raw type stays available as a tooltip. -import type { RunEvent, RunEventLevel, RunOutputLine } from '$lib/api'; +import type { RunEvent, RunEventLevel, RunNode, RunOutputLine } from '$lib/api'; import { eventTone } from '$lib/operate/labels'; +import { fullStamp } from './stamps'; +import { CHECK_FAILED_CODE } from './failures'; +import { checksOf, checksText, worstCheck, type CheckResult } from './checks'; import type { EventCategory } from '../types'; export const EVENT_CATEGORIES: { value: EventCategory; label: string }[] = [ { value: 'run', label: 'Run' }, { value: 'nodes', label: 'Nodes' }, { value: 'queries', label: 'Queries' }, - { value: 'checks', label: 'Checks' }, { value: 'output', label: 'Output' } ]; export function eventCategory(e: RunEvent): EventCategory { if (e.type.startsWith('statement_')) return 'queries'; - if (e.type.startsWith('resource_attempt_')) return 'nodes'; + if (e.type.startsWith('resource_attempt_') || e.type === 'node_log') return 'nodes'; if (e.type === 'audit_completed') return 'checks'; return 'run'; } @@ -23,17 +25,22 @@ export function eventSummary(e: RunEvent): string { switch (e.type) { case 'requested': return e.message; + case 'node_log': + // A Python node's `ctx.log` line, as it wrote it. + return e.message.replace(/^\[warning\] /, ''); case 'queued': return 'Queued'; case 'claimed': return 'Claimed write lock'; case 'launched': - return 'Container started'; + return e.message || 'Worker started'; case 'cancel_requested': return e.message; case 'presumed_failed': return 'Lost contact · failed'; case 'terminated': + // A run that never started says so, in the same words everywhere. + if (/^Terminated: skipped/.test(e.message)) return 'Not started'; return `Finished${e.message.match(/^Terminated: (\w+)/) ? `: ${e.message.match(/^Terminated: (\w+)/)![1].replace('_', ' ')}` : ''}`; case 'invocation_started': return 'sqb started'; @@ -84,8 +91,30 @@ export type LogEntry = { queries: LogEntry[]; /** Shown even with printed output hidden: a failing run's last printed block, which ends with its failures. */ pinned: boolean; + /** A short tag in plain words (built, merged, failed, skipped, check, run) and its colour. */ + tag?: { text: string; tone: string }; + /** A node line's node: its failure, file and statements, for what its details open to. */ + node?: RunNode; + /** A node line's checks, problems first, for the table its details open to. */ + checks?: CheckResult[]; + /** A capped live view's marker: this many earlier lines of the node's output are in the viewer. */ + omitted?: number; + /** Structured details the row opens to in place, as key and value; `long` is text behind "show more". */ + details?: [string, string][]; + long?: string; }; +const TAG_TONE = { ok: 'var(--sb-success)', err: 'var(--sb-error)', warn: 'var(--sb-warning)', run: 'var(--sb-running)', quiet: 'var(--sb-text-faint)' }; +/** The tag an event's row carries: plain words, never the event type. */ +function eventTag(e: RunEvent): LogEntry['tag'] { + if (e.type === 'resource_attempt_completed') return { text: 'built', tone: TAG_TONE.ok }; + if (e.type === 'resource_attempt_failed' || e.type === 'statement_failed' || e.type === 'invocation_failed') return { text: 'failed', tone: TAG_TONE.err }; + if (e.type === 'resource_attempt_skipped') return { text: 'skipped', tone: TAG_TONE.quiet }; + if (e.type === 'audit_completed') return { text: 'check', tone: e.level === 'info' ? TAG_TONE.ok : TAG_TONE.warn }; + if (e.type === 'node_log') return { text: 'log', tone: e.level === 'info' ? TAG_TONE.quiet : TAG_TONE.warn }; + return { text: 'run', tone: TAG_TONE.quiet }; +} + const QUERY_DONE = new Set(['statement_completed', 'statement_failed']); const NODE_ENDS = new Set(['resource_attempt_completed', 'resource_attempt_failed', 'resource_attempt_skipped']); @@ -104,7 +133,9 @@ function entryOf(e: RunEvent): LogEntry { stream: null, statementId: e.statementId, queries: [], - pinned: false + pinned: false, + tag: eventTag(e), + details: e.message && e.message !== text ? [['Message', e.message]] : undefined }; } @@ -114,7 +145,8 @@ function entryOf(e: RunEvent): LogEntry { * a failed query keeps its own row. Run-level bookkeeping queries and query progress are left to * the Statements tab. */ -export function logEntries(events: readonly RunEvent[], output: readonly (RunOutputLine & { runId: string })[]): LogEntry[] { +export function logEntries(events: readonly RunEvent[], output: readonly (RunOutputLine & { runId: string })[], outcomes?: NodeOutcomes): LogEntry[] { + if (outcomes) return withOutcomes(events, output, outcomes); const nodeOf = (e: RunEvent) => `${e.runId}|${e.nodeKey}`; const queries = new Map(); const ended = new Set(); @@ -156,3 +188,157 @@ export function logEntries(events: readonly RunEvent[], output: readonly (RunOut // A stable sort keeps each source's own order for equal times. return [...fromEvents, ...fromOutput].sort((a, b) => a.at.localeCompare(b.at)); } + +// ---- one line per node outcome ---- + +export type NodeOutcomes = { + nodes: readonly RunNode[]; + /** Why a skipped node was skipped, chain included, as the timeline says it. */ + skipCause: (n: RunNode) => string | null; + now: number; +}; + +/** A node line's tag: built or merged, a warned check, failed, skipped, building or not run. */ +/** + * A node line's tag names its build (built, merged, failed…), coloured by its worst outcome, checks + * included; never `check`, which is for checks run on their own, as in a `sqb test` run. + */ +function nodeTag(n: RunNode, checks: readonly RunEvent[]): LogEntry['tag'] { + if (n.status === 'success' || n.status === 'warn') { + const warned = n.status === 'warn' || checks.some((c) => c.level !== 'info'); + return { text: n.kind === 'incremental' ? 'merged' : 'built', tone: warned ? TAG_TONE.warn : TAG_TONE.ok }; + } + if (n.status === 'failed') return { text: 'failed', tone: TAG_TONE.err }; + if (n.status === 'skipped') return { text: 'skipped', tone: TAG_TONE.quiet }; + if (n.status === 'running') return { text: 'building', tone: TAG_TONE.run }; + return { text: 'not run', tone: TAG_TONE.quiet }; +} + +const secsText = (ms: number) => (ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`); +const BUILT: Record = { table: 'rebuilt table', view: 'rebuilt view', incremental: 'incremental merge', seed: 'loaded seed', loader: 'loaded', asset: 'ran asset' }; +const BUILDING: Record = { table: 'building table', view: 'building view', incremental: 'incremental merge', seed: 'loading seed', loader: 'loading', asset: 'running asset' }; +/** Kinds whose rows are what they added rather than what the table now holds. */ +const ADDS_ROWS = new Set(['incremental', 'loader']); + +/** + * The rows a node can honestly report: what an incremental merge or a load added, what a table rebuilt in + * full now holds, or, while it runs, what it has written so far; nothing for a view or an unknown count. + */ +export function rowsText(n: RunNode): string | null { + const count = (rows: number) => `${rows.toLocaleString('en-GB')} ${rows === 1 ? 'row' : 'rows'}`; + if (n.status === 'running') return n.rowsSoFar == null ? null : `${count(n.rowsSoFar)} so far`; + if (n.kind != null && ADDS_ROWS.has(n.kind)) return n.rowsAffected == null ? null : `+${count(n.rowsAffected)}`; + if (n.tableRows != null) return count(n.tableRows); + return null; +} + + +/** What a node did, on one line: its outcome, rows, time and checks, with a warning or failed check named on it. */ +export function outcomeText(n: RunNode, checks: readonly RunEvent[], skip: string | null, now: number): { text: string; level: RunEventLevel; tone: string } { + const took = n.startedAt ? secsText((n.endedAt ? Date.parse(n.endedAt) : now) - Date.parse(n.startedAt)) : null; + const rows = rowsText(n); + const join = (parts: (string | null | false)[]) => parts.filter(Boolean).join(' · '); + switch (n.status) { + case 'success': + case 'warn': { + // One line however many checks: the worst outcome sets its colour. + const results = checksOf(checks); + const warned = n.status === 'warn' || worstCheck(results) === 'warned' || worstCheck(results) === 'failed'; + if (n.noChangeReason && !warned) return { text: join(['✓ no change', n.noChangeReason, took, checksText(results)]), level: 'info', tone: 'var(--sb-text-faint)' }; + return { text: join([`${warned ? '⚠' : '✓'} ${BUILT[n.kind ?? 'table'] ?? `built ${n.kind}`}`, rows, took, checksText(results)]), level: warned ? 'warn' : 'info', tone: warned ? 'var(--sb-warning)' : 'var(--sb-success)' }; + } + case 'failed': { + // Built, then failed by an error-severity check: the build's line, with its checks. + if (n.errorCode === CHECK_FAILED_CODE) return { text: join([`✗ ${BUILT[n.kind ?? 'table'] ?? `built ${n.kind}`}`, rows, took, checksText(checksOf(checks))]), level: 'error', tone: 'var(--sb-error)' }; + const where = n.errorLocation ? (n.errorLocation.line == null ? n.errorLocation.file : `${n.errorLocation.file}:${n.errorLocation.line}`) : null; + return { text: join(['✗ failed', n.errorMessage ?? n.errorCode, where]), level: 'error', tone: 'var(--sb-error)' }; + } + case 'skipped': + return { text: join(['⊘ skipped', skip?.replace(/^skipped: /, '') ?? null]), level: 'info', tone: 'var(--sb-text-faint)' }; + case 'running': + return { text: join([`▸ ${BUILDING[n.kind ?? 'table'] ?? `building ${n.kind}`}`, rows, took && `${took} so far`]), level: 'info', tone: 'var(--sb-running)' }; + case 'pending': + return { text: '· waiting', level: 'info', tone: 'var(--sb-text-faint)' }; + default: + return { text: '— not run', level: 'info', tone: 'var(--sb-text-faint)' }; + } +} + +/** + * The log with one line per node: where the node started, saying what it did once done (and what it is + * doing while it builds), with its checks folded in. Run-level events stay as they are; what sqb printed + * for a node carries the node, so filtering by node keeps it. + */ +function withOutcomes(events: readonly RunEvent[], output: readonly (RunOutputLine & { runId: string })[], { nodes, skipCause, now }: NodeOutcomes): LogEntry[] { + const id = (runId: string, key: string) => `${runId}|${key}`; + const known = new Map(nodes.map((n) => [id(n.runId, n.nodeKey), n])); + const byNode = new Map(); + for (const e of events) if (e.nodeKey && known.has(id(e.runId, e.nodeKey))) byNode.set(id(e.runId, e.nodeKey), [...(byNode.get(id(e.runId, e.nodeKey)) ?? []), e]); + + // Run-level events, and a node's `ctx.log` lines, which keep their own rows. + const runLines = events.filter((e) => (e.type === 'node_log' || !(e.nodeKey && known.has(id(e.runId, e.nodeKey)))) && !e.type.startsWith('statement_')).map(entryOf); + // One failure, one line: a failed query of a node folds into the node's line, with its query in place. + const failedQueries = events.filter((e) => e.type === 'statement_failed' && !(e.nodeKey && known.has(id(e.runId, e.nodeKey)))).map(entryOf); + const nodeLines = nodes.flatMap((n): LogEntry[] => { + const evs = byNode.get(id(n.runId, n.nodeKey)) ?? []; + const at = n.startedAt ?? n.endedAt ?? evs[0]?.occurredAt; + if (!at || n.status === 'pending') return []; + const checks = evs.filter((e) => e.type === 'audit_completed'); + const o = outcomeText(n, checks, skipCause(n), now); + const where = n.errorLocation ? (n.errorLocation.line == null ? n.errorLocation.file : `${n.errorLocation.file}:${n.errorLocation.line}`) : null; + const details: [string, string][] = [ + ['Kind', n.kind ?? 'node'], + ...(n.startedAt ? [['Started', fullStamp(n.startedAt)] as [string, string]] : []), + ...(n.endedAt && n.startedAt ? [['Took', secsText(Date.parse(n.endedAt) - Date.parse(n.startedAt))] as [string, string]] : []), + ...(rowsText(n) ? [['Rows', rowsText(n)!] as [string, string]] : []), + ...(n.noChangeReason ? [['No change', n.noChangeReason] as [string, string]] : []), + ...(n.errorMessage ? [['Error', n.errorMessage] as [string, string]] : []), + ...(where ? [['Location', where] as [string, string]] : []), + ...(n.status === 'skipped' && skipCause(n) ? [['Why', skipCause(n)!.replace(/^skipped: /, '')] as [string, string]] : []), + ]; + return [ + { + id: `node-${n.runId}-${n.nodeKey}`, + runId: n.runId, + at, + nodeKey: n.nodeKey, + level: o.level, + category: 'nodes', + text: o.text, + title: evs.map((e) => `${e.type}: ${e.message}`).join('\n'), + tone: o.tone, + stream: null, + statementId: null, + queries: evs.filter((e) => QUERY_DONE.has(e.type)).map(entryOf), + pinned: false, + tag: nodeTag(n, checks), + details, + checks: checksOf(checks), + node: n, + long: n.errorDetail ?? undefined + } + ]; + }); + const failing = new Set(nodes.filter((n) => n.status === 'failed').map((n) => n.runId)); + const lastStderr = new Map(); + output.forEach((l, i) => l.stream === 'stderr' && failing.has(l.runId) && lastStderr.set(l.runId, i)); + const fromOutput = output.map( + (l, i): LogEntry => ({ + id: `out-${l.runId}-${i}`, + runId: l.runId, + at: l.at, + nodeKey: l.nodeKey ?? null, + omitted: l.omitted, + level: l.error ? 'error' : 'info', + category: 'output', + text: l.text, + title: l.stream, + tone: l.error ? 'var(--sb-error)' : l.stream === 'stderr' ? 'var(--sb-warning)' : 'var(--sb-text-faint)', + stream: l.stream, + statementId: null, + queries: [], + pinned: l.error || lastStderr.get(l.runId) === i + }) + ); + return [...runLines, ...nodeLines, ...failedQueries, ...fromOutput].sort((a, b) => a.at.localeCompare(b.at)); +} diff --git a/ui/src/routes/runs/[id]/utils/failures.test.ts b/ui/src/routes/runs/[id]/utils/failures.test.ts new file mode 100644 index 0000000000..4502ee0981 --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/failures.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest'; +import type { RunNode } from '$lib/api'; +import { errorHeadline, errorTextOf, tracebackOf } from './failures'; + +describe('a failed node’s error', () => { + it('finds a Python traceback in its text, from its first line, and none in a warehouse error', () => { + const printed = 'scoring batch 3\nTraceback (most recent call last):\n File "models/ml/score.py", line 9, in score\nKeyError: \'segment\''; + expect([tracebackOf(printed), tracebackOf('Division by zero'), tracebackOf(null)]).toEqual([ + 'Traceback (most recent call last):\n File "models/ml/score.py", line 9, in score\nKeyError: \'segment\'', + null, + null + ]); + }); + + it('reads its text from the node, else from the error read for it', () => { + const node = (extra: Partial) => ({ errorDetail: null, errorMessage: null, ...extra }) as RunNode; + const loaded = { nodeKey: 'model:orders', errorCode: null, message: 'Division by zero', file: null }; + expect([errorTextOf(node({ errorDetail: 'full text' }), loaded), errorTextOf(node({}), loaded), errorTextOf(node({ errorMessage: 'first line' }), null), errorTextOf(node({}), null)]).toEqual([ + 'full text', + 'Division by zero', + 'first line', + null + ]); + }); + + it('reads a traceback by its exception and any other error by its first line', () => { + const traceback = 'Traceback (most recent call last):\n ... 12 earlier lines\n File "models/ml/score.py", line 9, in score\n row["segment"]\nKeyError: \'segment\'\n'; + expect([errorHeadline(traceback), errorHeadline('Division by zero\nin margin_pct'), errorHeadline(null)]).toEqual(["KeyError: 'segment'", 'Division by zero', null]); + }); +}); diff --git a/ui/src/routes/runs/[id]/utils/failures.ts b/ui/src/routes/runs/[id]/utils/failures.ts new file mode 100644 index 0000000000..29191239c5 --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/failures.ts @@ -0,0 +1,27 @@ +// How a failed node's error reads: a check that stopped it, or a Python exception's traceback. Pure. + +import type { RunNode, RunNodeError } from '$lib/api'; + +/** The error code sqb gives a node that failed on an error-severity check. */ +export const CHECK_FAILED_CODE = 'R006'; + +const TRACEBACK = 'Traceback (most recent call last):'; + +/** The Python traceback in an error's text, from its first line, or null when it holds none. */ +export function tracebackOf(text: string | null | undefined): string | null { + const at = text?.indexOf(TRACEBACK) ?? -1; + return text && at >= 0 ? text.slice(at) : null; +} + +/** A failed node's error text: what the node carries, or what was read for it on request. */ +export function errorTextOf(n: RunNode, loaded: RunNodeError | null): string | null { + return n.errorDetail ?? loaded?.message ?? n.errorMessage ?? null; +} + +/** An error's one line: a traceback's exception, such as `KeyError: 'segment'`, else its first line. */ +export function errorHeadline(text: string | null | undefined): string | null { + if (!text) return null; + const lines = text.split('\n').filter((l) => l.trim()); + if (!tracebackOf(text)) return lines[0] ?? null; + return [...lines].reverse().find((l) => /^[A-Za-z_][\w.]*(Error|Exception|Warning|Interrupt|Exit)\b/.test(l)) ?? lines.at(-1) ?? null; +} diff --git a/ui/src/routes/runs/[id]/utils/index.ts b/ui/src/routes/runs/[id]/utils/index.ts index 8f30eac6de..be13f1b429 100644 --- a/ui/src/routes/runs/[id]/utils/index.ts +++ b/ui/src/routes/runs/[id]/utils/index.ts @@ -1,8 +1,14 @@ export { axisTicks, formatSpan, formatTick, tickStep } from './axis'; export { bannersFor, cancelWords } from './banners'; export { costSummary, formatQueryCost, runCostOf } from '$lib/operate/cost'; -export { EVENT_CATEGORIES, eventCategory, eventSummary, logEntries, type LogEntry } from './events'; +export { EVENT_CATEGORIES, eventCategory, eventSummary, logEntries, rowsText, type LogEntry } from './events'; export { attemptLabel, retriedMembers } from './members'; export { groupNodes, notRunReason, progressOf } from './nodes'; -export { primaryChoice, rerunChoices } from './rerun'; +export { rerunChoices } from './rerun'; export { bottomTabs } from './tabs'; +export { QUICK_PICKS, quickPickText, withNameToggled, type QuickPick } from './picks'; +export { warehouseQueryUrl } from './queries'; +export { skipCause } from './skips'; +export { fullStamp } from './stamps'; +export { summaryOf, type RunSummary } from './summary'; +export { CHECK_FAILED_CODE, errorHeadline, errorTextOf, tracebackOf } from './failures'; diff --git a/ui/src/routes/runs/[id]/utils/nodes.ts b/ui/src/routes/runs/[id]/utils/nodes.ts index dcf0d60593..fbfb1acb78 100644 --- a/ui/src/routes/runs/[id]/utils/nodes.ts +++ b/ui/src/routes/runs/[id]/utils/nodes.ts @@ -7,7 +7,9 @@ const GROUPS: Omit[] = [ { key: 'failed', label: 'Failed', tone: 'var(--sb-error)', statuses: ['failed'] }, { key: 'skipped', label: 'Skipped', tone: 'var(--sb-warning)', statuses: ['skipped'] }, { key: 'succeeded', label: 'Succeeded', tone: 'var(--sb-success)', statuses: ['success', 'warn'] }, - { key: 'not_run', label: 'Not run', tone: 'var(--sb-text-faint)', statuses: ['cancelled', 'not_run'] } + { key: 'not_run', label: 'Not run', tone: 'var(--sb-text-faint)', statuses: ['cancelled', 'not_run'] }, + // Overlaps Succeeded: the summary line's "N warnings" filter. + { key: 'warned', label: 'With warnings', tone: 'var(--sb-warning)', statuses: ['warn'] } ]; /** diff --git a/ui/src/routes/runs/[id]/utils/page-memory.ts b/ui/src/routes/runs/[id]/utils/page-memory.ts new file mode 100644 index 0000000000..f611b9a2d2 --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/page-memory.ts @@ -0,0 +1,12 @@ +// What a run page showed, kept while the app is open, so Back from the output viewer, or +// any page a link opened, returns to the page exactly as it was: selection, filters, open rows, tab, +// drawer and scroll. It lives in memory only; a reload starts afresh. + +const pages = new Map>(); + +/** The remembered state of one run page, written as it changes. */ +export function pageMemory(runId: string): Record { + let memory = pages.get(runId); + if (!memory) pages.set(runId, (memory = {})); + return memory; +} diff --git a/ui/src/routes/runs/[id]/utils/picks.ts b/ui/src/routes/runs/[id]/utils/picks.ts new file mode 100644 index 0000000000..c787232dfd --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/picks.ts @@ -0,0 +1,31 @@ +// The quick picks that fill the selection to plan, and toggling one node's name in it. Pure. + +import type { RunNode } from '$lib/api'; +import { nodeLabel } from '$lib/operate/labels'; + +export type QuickPick = 'failed' | 'downstream' | 'skipped' | 'all'; + +export const QUICK_PICKS: { value: QuickPick; label: string }[] = [ + { value: 'failed', label: 'Failed' }, + { value: 'downstream', label: 'Failed + downstream' }, + { value: 'skipped', label: 'Skipped' }, + { value: 'all', label: 'All' } +]; + +/** + * The selector text a quick pick fills the selection with, in SQLBuild's syntax: names, `name+` for a + * node and its downstream, and the job's own selector (`job:shop_daily`) for All. + */ +export function quickPickText(pick: QuickPick, nodes: readonly RunNode[], jobKey: string | null): string { + const names = (keep: (n: RunNode) => boolean) => [...new Set(nodes.filter(keep).map((n) => nodeLabel(n.nodeKey)))]; + if (pick === 'failed') return names((n) => n.status === 'failed').join(' '); + if (pick === 'downstream') return names((n) => n.status === 'failed').map((name) => `${name}+`).join(' '); + if (pick === 'skipped') return names((n) => n.status === 'skipped').join(' '); + return jobKey ? `job:${jobKey}` : names(() => true).join(' '); +} + +/** The selection text with `name` added, or removed when it is already there as a plain name. */ +export function withNameToggled(text: string, name: string): string { + const tokens = text.split(/\s+/).filter(Boolean); + return (tokens.includes(name) ? tokens.filter((t) => t !== name) : [...tokens, name]).join(' '); +} diff --git a/ui/src/routes/runs/[id]/utils/queries.ts b/ui/src/routes/runs/[id]/utils/queries.ts new file mode 100644 index 0000000000..1be3cc90c5 --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/queries.ts @@ -0,0 +1,9 @@ +// Where a warehouse shows one of its queries. Pure. + +/** + * A warehouse query's page in its console, or null where the adapter has none (only Snowflake's query detail so far). + */ +export function warehouseQueryUrl(adapter: string | null | undefined, queryId: string): string | null { + if (adapter === 'snowflake') return `https://app.snowflake.com/#/compute/history/queries/${encodeURIComponent(queryId)}/detail`; + return null; +} diff --git a/ui/src/routes/runs/[id]/utils/rerun.test.ts b/ui/src/routes/runs/[id]/utils/rerun.test.ts new file mode 100644 index 0000000000..21b2dd9f36 --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/rerun.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest'; +import type { RunDetail, RunRow } from '$lib/api'; +import { eligible } from '../../utils/bulk'; +import { rerunChoices } from './rerun'; + +const detail = (status: string, unfinished: string[]) => + ({ run: { status, kind: 'job', rewriteHistory: false }, rerunFromFailureNodes: unfinished }) as unknown as RunDetail; +const row = (status: string, count: number) => ({ run: { status }, rerunFromFailureCount: count }) as unknown as RunRow; + +describe('rerun of a cancelled run', () => { + it.each([ + ['with unfinished steps', ['asset:fulfil[pack]', 'asset:fulfil[ship]'], 'from_failure', true], + ['with every step finished', [], 'all', false] + ] as const)('%s', (_, unfinished, expectedFirstOffered, expectedEligible) => { + const cancelled = detail('cancelled', [...unfinished]); + const choices = rerunChoices(cancelled, [], () => true); + expect(choices.find((c) => !c.disabledReason)?.mode).toBe(expectedFirstOffered); + expect(choices.find((c) => c.mode === 'from_failure')?.disabledReason === null).toBe(expectedEligible); + expect(eligible('from_failure', row('cancelled', unfinished.length))).toBe(expectedEligible); + }); +}); diff --git a/ui/src/routes/runs/[id]/utils/rerun.ts b/ui/src/routes/runs/[id]/utils/rerun.ts index 1eac630ddc..38d2829b3d 100644 --- a/ui/src/routes/runs/[id]/utils/rerun.ts +++ b/ui/src/routes/runs/[id]/utils/rerun.ts @@ -28,8 +28,8 @@ export function rerunChoices(detail: RunDetail, selected: readonly string[], can choices.push({ mode: 'from_failure', label: 'Rerun from failure', - help: failures ? `${plural(failures, 'failed or skipped node')}` : 'Nothing failed', - disabledReason: common ?? (failures ? null : 'Nothing failed or was skipped in this run') + help: failures ? `${plural(failures, 'unfinished node')}` : 'Every node finished', + disabledReason: common ?? (failures ? null : 'Nothing failed, was cancelled or was skipped in this run') }); choices.push({ mode: 'all', @@ -39,10 +39,3 @@ export function rerunChoices(detail: RunDetail, selected: readonly string[], can }); return choices; } - -/** The split button's main action: from failure after a failure, otherwise all. */ -export function primaryChoice(detail: RunDetail, choices: RerunChoice[]): RerunChoice { - const failedLike = detail.run.status === 'failed' || detail.run.status === 'partial' || detail.run.status === 'presumed_failed'; - const wanted = failedLike && detail.rerunFromFailureNodes.length ? 'from_failure' : 'all'; - return choices.find((c) => c.mode === wanted)!; -} diff --git a/ui/src/routes/runs/[id]/utils/skips.ts b/ui/src/routes/runs/[id]/utils/skips.ts new file mode 100644 index 0000000000..5b3d331692 --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/skips.ts @@ -0,0 +1,21 @@ +// Why a skipped node was skipped, naming the chain of skips back to the failure. Pure. + +import type { RunEdge, RunNode } from '$lib/api'; +import { nodeLabel } from '$lib/operate/labels'; + +/** + * Why a skipped node was skipped, on one line, naming the chain: a node under a failure says that node + * failed; one under another skipped node says that node was skipped, and after which failure. + */ +export function skipCause(n: RunNode, nodes: readonly RunNode[], edges: readonly RunEdge[]): string | null { + if (n.status !== 'skipped') return null; + const why = n.skippedBecauseOf; + if (!why) return 'skipped: an upstream node did not run'; + const across = why.runId !== n.runId ? ` in ${why.jobKey ?? why.runId}` : ''; + const byKey = new Map(nodes.map((x) => [x.nodeKey, x])); + const parents = edges.filter((e) => e.to === n.nodeKey).map((e) => byKey.get(e.from)); + if (parents.some((p) => p?.nodeKey === why.nodeKey)) return `skipped: ${nodeLabel(why.nodeKey)} failed${across}`; + const via = parents.find((p) => p?.status === 'skipped' && p.skippedBecauseOf?.nodeKey === why.nodeKey); + if (via) return `skipped: ${nodeLabel(via.nodeKey)} was skipped (after ${nodeLabel(why.nodeKey)} failed${across})`; + return `skipped: ${nodeLabel(why.nodeKey)} failed${across}`; +} diff --git a/ui/src/routes/runs/[id]/utils/stamps.ts b/ui/src/routes/runs/[id]/utils/stamps.ts new file mode 100644 index 0000000000..c0655a4d0e --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/stamps.ts @@ -0,0 +1,8 @@ +// Full local timestamps for the log and the drawer. Pure. + +/** A full local timestamp with milliseconds, such as `2026-11-20 09:22:51.204`. */ +export function fullStamp(iso: string): string { + const d = new Date(iso); + const p = (n: number, w = 2) => String(n).padStart(w, '0'); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}.${p(d.getMilliseconds(), 3)}`; +} diff --git a/ui/src/routes/runs/[id]/utils/summary.test.ts b/ui/src/routes/runs/[id]/utils/summary.test.ts new file mode 100644 index 0000000000..658131e1f3 --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/summary.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest'; +import type { RunEdge, RunEvent, RunNode } from '$lib/api'; +import { rowsText } from './events'; +import { quickPickText, withNameToggled } from './picks'; +import { skipCause } from './skips'; +import { summaryOf } from './summary'; + +const node = (nodeKey: string, status: RunNode['status'], extra: Partial = {}) => ({ nodeKey, status, runId: 'r', kind: 'table', rowsAffected: null, skippedBecauseOf: null, ...extra }) as RunNode; +const check = (level: RunEvent['level']) => ({ type: 'audit_completed', level }) as RunEvent; + +describe('a run’s summary line', () => { + it('counts what it built, what incrementals added, and its problems and checks', () => { + const nodes = [ + node('model:orders', 'success'), + node('model:events', 'success', { kind: 'incremental', rowsAffected: 48_000 }), + node('model:margin', 'warn'), + node('model:stock', 'failed'), + node('model:report', 'skipped'), + node('model:late', 'not_run') + ]; + expect(summaryOf(nodes, [check('info'), check('info'), check('warn')], false)).toEqual({ + built: 3, + incremental: 1, + incrementalRows: 48_000, + failed: 1, + warned: 1, + skipped: 1, + notRun: 1, + running: 0, + waiting: 0, + checksPassed: 2, + checksWarned: 1, + checksFailed: 0 + }); + }); + + it('counts nodes that have not started as waiting while the run goes on, and as not run once it ended', () => { + const nodes = [node('model:orders', 'running'), node('model:report', 'pending')]; + expect([summaryOf(nodes, [], true).waiting, summaryOf(nodes, [], false).notRun]).toEqual([1, 1]); + }); +}); + +describe('why a node was skipped', () => { + const failed = node('source:raw_orders', 'failed'); + const loader = node('loader:orders', 'skipped', { skippedBecauseOf: { nodeKey: 'source:raw_orders', runId: 'r', jobKey: null } }); + const model = node('model:orders', 'skipped', { skippedBecauseOf: { nodeKey: 'source:raw_orders', runId: 'r', jobKey: null } }); + const edges: RunEdge[] = [ + { from: 'source:raw_orders', to: 'loader:orders' }, + { from: 'loader:orders', to: 'model:orders' } + ]; + + it('names the failure under it, and the skipped node between it and a failure further up', () => { + const all = [failed, loader, model]; + expect([skipCause(loader, all, edges), skipCause(model, all, edges), skipCause(failed, all, edges)]).toEqual([ + 'skipped: raw_orders failed', + 'skipped: orders was skipped (after raw_orders failed)', + null + ]); + }); +}); + +describe('quick picks', () => { + const nodes = [node('model:orders', 'failed'), node('model:report', 'skipped'), node('model:customers', 'success')]; + + it('fill the selection with the failed, their downstream, the skipped, or the whole job', () => { + expect([quickPickText('failed', nodes, 'shop_daily'), quickPickText('downstream', nodes, 'shop_daily'), quickPickText('skipped', nodes, 'shop_daily'), quickPickText('all', nodes, 'shop_daily'), quickPickText('all', nodes, null)]).toEqual([ + 'orders', + 'orders+', + 'report', + 'job:shop_daily', + 'orders report customers' + ]); + }); + + it('toggle one node’s plain name in the selection', () => { + expect([withNameToggled('orders report', 'report'), withNameToggled('orders', 'report'), withNameToggled('', 'orders')]).toEqual(['orders', 'orders report', 'orders']); + }); +}); + +describe('a node’s rows', () => { + it('are only what it can report: rows added, a rebuilt table’s count, or rows so far', () => { + expect([ + rowsText(node('model:events', 'success', { kind: 'incremental', rowsAffected: 1200 })), + rowsText(node('loader:raw_events', 'success', { kind: 'loader', rowsAffected: 1 })), + rowsText(node('model:orders', 'success', { tableRows: 5000, rowsAffected: 5000 })), + rowsText(node('model:orders', 'running', { rowsSoFar: 320 })), + rowsText(node('model:orders_view', 'success', { kind: 'view' })), + rowsText(node('model:orders', 'running')) + ]).toEqual(['+1,200 rows', '+1 row', '5,000 rows', '320 rows so far', null, null]); + }); +}); diff --git a/ui/src/routes/runs/[id]/utils/summary.ts b/ui/src/routes/runs/[id]/utils/summary.ts new file mode 100644 index 0000000000..b087ba921f --- /dev/null +++ b/ui/src/routes/runs/[id]/utils/summary.ts @@ -0,0 +1,39 @@ +// What a run did, for the line under its header: what it built, what failed or was skipped, and its checks. Pure. + +import type { RunEvent, RunNode } from '$lib/api'; + +export type RunSummary = { + built: number; + incremental: number; + incrementalRows: number; + failed: number; + warned: number; + skipped: number; + notRun: number; + running: number; + waiting: number; + checksPassed: number; + checksWarned: number; + checksFailed: number; +}; + +/** What the run did, for the line under the header: built nodes and the rows incrementals added, failures, skips and checks. */ +export function summaryOf(nodes: readonly RunNode[], events: readonly RunEvent[], active: boolean): RunSummary { + const built = nodes.filter((n) => n.status === 'success' || n.status === 'warn'); + const incremental = built.filter((n) => n.kind === 'incremental'); + const checks = events.filter((e) => e.type === 'audit_completed'); + return { + built: built.length, + incremental: incremental.length, + incrementalRows: incremental.reduce((sum, n) => sum + (n.rowsAffected ?? 0), 0), + failed: nodes.filter((n) => n.status === 'failed').length, + warned: nodes.filter((n) => n.status === 'warn').length, + skipped: nodes.filter((n) => n.status === 'skipped').length, + notRun: nodes.filter((n) => n.status === 'not_run' || n.status === 'cancelled' || (!active && n.status === 'pending')).length, + running: nodes.filter((n) => n.status === 'running').length, + waiting: active ? nodes.filter((n) => n.status === 'pending').length : 0, + checksPassed: checks.filter((e) => e.level === 'info').length, + checksWarned: checks.filter((e) => e.level === 'warn').length, + checksFailed: checks.filter((e) => e.level === 'error').length + }; +} diff --git a/ui/src/routes/settings/+page.svelte b/ui/src/routes/settings/+page.svelte index 7f9a7db1bb..5be391d7a6 100644 --- a/ui/src/routes/settings/+page.svelte +++ b/ui/src/routes/settings/+page.svelte @@ -24,7 +24,8 @@ oidc: 'Single sign-on (OIDC)', trusted_proxy: 'Trusted proxy', password: 'Password', - disabled: 'Off (local only)' + disabled: 'Off (local only)', + keys: 'Service account keys only' }; diff --git a/ui/src/routes/triggers/[id]/sensor-panel.svelte b/ui/src/routes/triggers/[id]/sensor-panel.svelte index 2edf71041f..3f8c76f12c 100644 --- a/ui/src/routes/triggers/[id]/sensor-panel.svelte +++ b/ui/src/routes/triggers/[id]/sensor-panel.svelte @@ -129,10 +129,11 @@ {formatAgo(e.requestedAt, app.now)} {#if e.eventId}{e.eventId}{:else}Poll{/if} - + {#if e.outcome === 'skipped' && !e.skippedBy}{e.skipReason ?? ''}{/if} {#if e.runIds.length}→ {#each e.runIds as id, i (id)}{i ? ', ' : ''}{shortRunId(id)}{/each}{/if} - {#if e.outcome === 'failed' || e.outcome === 'timed_out'} + {#if e.unreadable}{e.unreadable} + {:else if e.outcome === 'failed' || e.outcome === 'timed_out'} {#if e.error}
    {e.error.split('\n').at(-1)}
    {e.error}
    {:else}{e.failureCode ?? e.outcome}{/if} {/if} {#if e.skippedBy}Skipped by {e.skippedBy}{#if e.skipReason}: {e.skipReason}{/if}{/if} diff --git a/website/examples/waffle-shop/materializations/partition_tracked.py b/website/examples/waffle-shop/materializations/partition_tracked.py index 6f7487fa0c..b5360d4e9e 100644 --- a/website/examples/waffle-shop/materializations/partition_tracked.py +++ b/website/examples/waffle-shop/materializations/partition_tracked.py @@ -36,11 +36,11 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) if ctx.is_full_refresh: - ctx.log("clearing partition tracking state") + ctx.log.info("clearing partition tracking state") ctx.execute_sql(f"DELETE FROM {tracking_table}") all_partitions: list[str] = _generate_date_range(date_start, date_end) - ctx.log("checking for stale partitions") + ctx.log.info("checking for stale partitions") stale: list[str] = _find_stale_partitions(ctx, tracking_table, all_partitions) if not stale: @@ -68,7 +68,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: if ctx.on_progress is not None: ctx.on_progress(f"partition {i + 1}/{len(stale)}: {partition_value}") - ctx.log(f"building partition {partition_value}") + ctx.log.info(f"building partition {partition_value}") ctx.adapter.drop( connection=ctx.connection, @@ -95,7 +95,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) if not target_exists: - ctx.log("promoting first partition into target") + ctx.log.info("promoting first partition into target") ctx.adapter.rename( connection=ctx.connection, origin=staging, @@ -104,7 +104,7 @@ def materialize(ctx: MaterializationContext) -> MaterializationResult: ) target_exists = True else: - ctx.log("promoting partition into target") + ctx.log.info("promoting partition into target") ctx.execute_sql( f"DELETE FROM {ctx.destination} " f"WHERE CAST({partition_col} AS DATE) >= CAST('{partition_value}' AS DATE) " diff --git a/website/src/content/docs/docs/cli/build.mdx b/website/src/content/docs/docs/cli/build.mdx index 3686481639..3de1d7aaf5 100644 --- a/website/src/content/docs/docs/cli/build.mdx +++ b/website/src/content/docs/docs/cli/build.mdx @@ -42,6 +42,7 @@ own option. `--version` works only directly after `sqb`, as in `sqb --version`: | `--no-python` | Skip read-side Python assets (loader-side Python still runs for selected sources) | | `--no-sql-analysis` | Disable compile-time SQL analysis (`--no-sql-validation` is an alias) | | `--no-cache` | Bypass the reusable compile-analysis cache for this invocation | +| `--discover` | Run the project's `@discover` functions with the target's providers for this command, instead of compiling each `for_each` asset as its placeholder; nothing is saved. See [Discovered nodes](/docs/concepts/python-nodes/discovered-nodes) | | `--full-refresh` | Drop and rebuild selected models unless a model sets `full_refresh false`; `full_refresh true` forces a model even without this flag | | `--no-job-settings` | Ignore the settings of the jobs the selection names; see [Settings when a build names a job](/docs/concepts/orchestration#settings-when-a-build-names-a-job) | | `--changed` | Build only the selected models and seeds that changed, and what they reach downstream; `--changed=definition,source_data` picks what counts. See [Building only what changed](#building-only-what-changed) | @@ -242,6 +243,17 @@ Without `--debug`, a statement that is still running after 30 seconds prints a ` 30 seconds, with its elapsed time and, when the warehouse reports one, its query ID. A failed statement or step still prints its `FAIL` row. +When output isn't a terminal, as in CI logs or a worker's captured output, a node that runs for +more than 30 seconds also brings one line naming the nodes still running, longest first, with the +rows a loader or microbatch model has written so far where it reports them: + +``` +… still running (3) stg_inventory 2m10s · stg_shipments 1m50s · raw_events 1m05s (48,210 rows) +``` + +It names up to three nodes and counts the rest as `+N more`. While nodes keep running it repeats +after 1 minute, then 2 minutes, then every 5 minutes. A terminal shows its live view instead. + ## Deferred builds Use `--defer-to` to resolve unselected model references against another target. This lets you build a subset of models in dev while referencing production tables for everything else: diff --git a/website/src/content/docs/docs/cli/compile.mdx b/website/src/content/docs/docs/cli/compile.mdx index 27f042fca0..dc5fec4da2 100644 --- a/website/src/content/docs/docs/cli/compile.mdx +++ b/website/src/content/docs/docs/cli/compile.mdx @@ -50,6 +50,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `--exclude` | Remove resources from the selected scope | | `--no-sql-analysis` | Turn off SQL syntax, binding, type inference and semantic checks (`--no-sql-validation` is an alias) | | `--no-cache` | Compile in full, without reusing earlier compiles or the Rules cache; see [Forcing a fresh compile](#forcing-a-fresh-compile) | +| `--discover` | Run the project's `@discover` functions with the target's providers for this command, instead of compiling each `for_each` asset as its placeholder; nothing is saved. See [Discovered nodes](/docs/concepts/python-nodes/discovered-nodes) | | `--allow-missing-secrets` | Run without provider secrets; see [Secrets](/docs/concepts/python-nodes/providers#secrets) | | `--defer-to` | Resolve unselected model references against another target | | `--json` | Print the full compile report as JSON | diff --git a/website/src/content/docs/docs/cli/dev.mdx b/website/src/content/docs/docs/cli/dev.mdx index a04b52472e..70cf48af95 100644 --- a/website/src/content/docs/docs/cli/dev.mdx +++ b/website/src/content/docs/docs/cli/dev.mdx @@ -44,13 +44,52 @@ and how to fix it. | Option | Default | Effect | | --- | --- | --- | -| `--port` | `8000` | Port to listen on, on `127.0.0.1`. `0` picks a free port | +| `--port` | `8000` | Port to listen on. `0` picks a free port | +| `--host` | `127.0.0.1` | IP address to listen on; see [Open it to a proxy or a network](#open-it-to-a-proxy-or-a-network) | +| `--allow-host` | None | Also accept this name in `Host` and `Origin`; repeat it for more names | | `--target` | The configured target | Target to compile and run | | `--control-store-url` | `.sqlbuild/control.sqlite3` in the project | Control store URL or path | | `--no-scheduler` | Off | Serve and reload without running scheduled work | | `--triggers` | Off | Keep each trigger's default status and your changes to it, instead of pausing every trigger at start-up | | `--plain` | Off, unless stdout or stderr is not a terminal | Print appended lines instead of redrawing the screen; see [Plain output](#plain-output) | +## Open it to a proxy or a network + +By default `sqb dev` listens on `127.0.0.1` and answers only requests whose `Host`, and `Origin` +when there is one, are local. That stops other websites in your browser from using the session, +which has no sign-in. + +:::danger +With `--host` beyond loopback or with `--allow-host`, anyone who can reach that address or name has +full access without signing in and with your credentials: they can change and run what the project +can, against your warehouse. These options don't identify callers. A client other than a browser +can send any `Host` it likes, so only the network or the proxy limits who gets in. +::: + +Use them only for your own session, or for one shared on purpose with people you would hand your +credentials to, on a trusted network. Use [`sqb server`](/docs/cli/server/) for anything else: when +people need their own accounts or roles, or the address is reachable by anyone you don't trust. + +Behind a reverse proxy on the same machine, allow the name people browse to: + +```bash +sqb dev --allow-host control.example.com +``` + +On a trusted network without a proxy, listen on the network and allow each name or IP address that +people browse to: + +```bash +sqb dev --host 0.0.0.0 --allow-host buildbox.example.com --allow-host 192.0.2.10 +``` + +An allowed name works over HTTP and HTTPS on the default ports and on `sqb dev`'s own port. For a +proxy on another port, include it: `--allow-host control.example.com:8443`. A name given with a +port works only on that port. Write names without a scheme or path; there are no wildcards. Every +other name stays refused, including when listening on `0.0.0.0`, so other websites and DNS +rebinding are still blocked. When either option opens the session, a **No sign-in** warning at +start-up and the ready box's **Access** row say who gets in. + ## Set provider secrets `sqb dev` loads the project's [env file](/docs/concepts/project-configuration#env-file), `.env` @@ -60,16 +99,26 @@ interpreter when a value changed, so the next compile and run use the new values in the shell that started `sqb dev` still win. While a provider is missing secrets that the target doesn't -[allow to be missing](/docs/concepts/project-configuration#allowed-missing-secrets), a **Secrets missing** warning above the -keys names the provider and the variables it reads, never their values: +[allow to be missing](/docs/concepts/project-configuration#allowed-missing-secrets), `sqb dev` +keeps running and prints a warning with each field's file and line, the variable it reads, the +nodes that need the provider (the first five, then a count) and the fix, never a value: ```text -⚠ Secrets missing region WORKER_TOKEN, REGION_CODE; set them in .env or - the environment; press r to reload +⚠ warn 1 provider has missing secrets missing secret + at providers/region.py:9 region_token ← REGION_TOKEN + providers/region.py:10 region_code ← REGION_CODE + why runs that use it stop at the provider check, before the warehouse; 2 + nodes need it (raw_regions, stg_regions) + fix set them in .env and press r, or set them in the environment you + start sqb dev from, then quit and run sqb dev again ``` -Runs that use the provider stop before they reach the warehouse. The warning clears once the next -publication finds every secret set; with `--plain`, a `Secrets set` line says so. +`r` picks up an edit to the env file, which the fix names when the target uses another one. It +can't pick up a variable exported in a shell afterwards: for that, quit and run `sqb dev` again. + +The warning is printed again when the missing variables change, and a **Secrets missing** row stays +above the keys meanwhile. Once the next publication finds every secret set, the row clears and a +`Secrets set` line says so. ## Sign in to the warehouse @@ -190,8 +239,9 @@ timed reads but not the read after each publication or run. ## Details -- `sqb dev` listens only on loopback and needs no sign-in. Use [`sqb server`](/docs/cli/server/) - for a server other people or machines connect to. +- `sqb dev` needs no sign-in and listens only on loopback unless you + [open it up](#open-it-to-a-proxy-or-a-network). Use [`sqb server`](/docs/cli/server/) for a + server other people or machines connect to. - The control store keeps runs, trigger changes and history between sessions. Delete `.sqlbuild/control.sqlite3` to start again from nothing. - The location is named after the project, the `name` in `sqlbuild_project.toml`. When the diff --git a/website/src/content/docs/docs/cli/location.mdx b/website/src/content/docs/docs/cli/location.mdx index 01709066a3..2865abe140 100644 --- a/website/src/content/docs/docs/cli/location.mdx +++ b/website/src/content/docs/docs/cli/location.mdx @@ -13,9 +13,15 @@ export SQLBUILD_LOCATION_TOKEN=... sqb location serve --server https://control.example.com --location-id "$LOCATION_ID" --target production ``` +With a separate `sqb server`, keep a SQLite control database and a local +[output folder](/docs/cli/server/#keep-run-output) outside the project or under the project's +`.sqlbuild` folder. Otherwise the location takes their writes for project edits and publishes again. + Create the location and its token with `sqb admin create-location orders` and -`sqb admin issue-location-token` on the server's host. The location reads the token from -`SQLBUILD_LOCATION_TOKEN` and never opens the control database. +`sqb admin issue-location-token` on the server's host. The token is the only thing on stdout, so +`export SQLBUILD_LOCATION_TOKEN="$(sqb admin issue-location-token "$LOCATION_ID" --expires-at "$EXPIRY")"` +captures it. The location reads it from `SQLBUILD_LOCATION_TOKEN` and never opens the control +database. ## Check a location's health @@ -34,6 +40,7 @@ sqb location health --server https://control.example.com --location-id "$LOCATIO | `healthy` | An instance checked in within 90 seconds and its last load published | `0` | | `degraded` | The warehouse connection check after the last load failed | `0` | | `missing_secrets` | A provider [secret](/docs/concepts/python-nodes/providers#secrets) is unset in the location's environment, and the target's [`allow_missing_secrets`](/docs/concepts/project-configuration#allowed-missing-secrets) doesn't list the provider, so runs that use it fail | `1` | +| `discovery_failed` | A [discover function](/docs/concepts/python-nodes/discovered-nodes) failed at the last publication, so its set serves its last good items, or none | `0` | | `falling_back` | The last load failed, so runs use the previous snapshot | `1` | | `broken` | No instance has checked in for 90 seconds | `1` | @@ -69,8 +76,8 @@ A `missing_secrets` location publishes and runs jobs whose nodes have their secr publishes it reports the providers missing secrets, with their variables and the nodes that use them, and prints them in its output. Its page in the UI lists them, and the Overview shows the problem. A run that needs one fails those nodes with `D012` before connecting to the warehouse and -skips the nodes that read them. Set the missing variables in its environment or env file and -restart it; `sqb debug` in the location lists them too. A provider the target allows to miss its +skips the nodes that read them. Set the missing variables in its env file or in the environment it +was started with, then restart it (under `sqb dev`, `r` is enough after editing the env file); `sqb debug` in the location lists them too. A provider the target allows to miss its secrets shows as a note on the location's page instead. ## Provide settings and secrets @@ -88,3 +95,55 @@ The location stops at start-up with an error naming the file when it doesn't exi set in the container or service environment win over the file. After changing the file, restart the location so its compiles and plan previews use the new values. Each [worker](/docs/cli/server/) reads the file when its run starts. + +## Republish + +Ask a served location to compile and publish again, for example after a deploy of a system its +[discover functions](/docs/concepts/python-nodes/discovered-nodes) read from. Every discover +function runs, as with `r` in `sqb dev`. + +With an API key, from the environment and never an argument, the server may be `http://` or +`https://`, so a server on a private network needs no TLS: + +```bash +export SQLBUILD_API_KEY=... +sqb location republish --server http://control.internal.example.com:8000 --location-id "$LOCATION_ID" \ + --target production --reason "fulfilment 0.58.0 deployed" --wait +``` + +A key sent over plain HTTP to another host prints one warning, because anyone on the network path +can read it. Without `SQLBUILD_API_KEY` the command uses your [`sqb login`](/docs/cli/login) session, +which needs `https://`; `--ca-cert` trusts a private CA for it. + +| Outcome | Exit code | +| --- | --- | +| Accepted, without `--wait`; or published | `0` | +| The publish failed, or no location took the request within 15 minutes | `1` | +| The request was refused or got no answer, or `--wait` ended after `--timeout` seconds (default 600) | `2` | + +The JSON result has `requested_by`, `requested_at` and `state` (`pending`, `published`, `failed` or +`expired`), with `snapshot_id` after a publish or `error` after a failed one. + +The same request with `curl`: + +```bash +BASE="http://control.internal.example.com:8000/api/control/locations/$LOCATION_ID/targets/production" +REQUEST_ID=$(uuidgen) + +curl --fail -X POST "$BASE/republish?wait=10" \ + -H "Authorization: Bearer $SQLBUILD_API_KEY" -H "Content-Type: application/json" \ + -d "{\"request_id\": \"$REQUEST_ID\", \"reason\": \"fulfilment 0.58.0 deployed\"}" + +# While the state is pending, ask again +curl --fail "$BASE/republish/$REQUEST_ID?wait=10" -H "Authorization: Bearer $SQLBUILD_API_KEY" + +# Each discovered set's status, fetch time, digest and tags in the current snapshot +curl --fail "$BASE/discovered" -H "Authorization: Bearer $SQLBUILD_API_KEY" +``` + +- `wait` holds a response open for at most 60 seconds. Reusing a `request_id` queues nothing new. +- Republishing needs `location.republish`, which the operator, developer and admin roles have. + Reading `discovered` needs `view`. +- A failed discover function doesn't fail the publish, as its set keeps its last good items. Check + the set's `status` and `tags` in `discovered` to confirm a deploy. +- The audit log records who asked and why, and the location prints both. diff --git a/website/src/content/docs/docs/cli/plan.mdx b/website/src/content/docs/docs/cli/plan.mdx index e1e6fdcc35..9c57635d4b 100644 --- a/website/src/content/docs/docs/cli/plan.mdx +++ b/website/src/content/docs/docs/cli/plan.mdx @@ -21,6 +21,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb |------|-------------| | `--no-sql-analysis` | Disable compile-time SQL analysis (`--no-sql-validation` is an alias) | | `--no-cache` | Bypass the reusable compile-analysis cache for this invocation | +| `--discover` | Run the project's `@discover` functions with the target's providers for this command, instead of compiling each `for_each` asset as its placeholder; nothing is saved. See [Discovered nodes](/docs/concepts/python-nodes/discovered-nodes) | | `--no-python` | Exclude read-side Python assets from the plan | | `--defer-to` | Resolve unselected model references against another target | | `--plan-from` | Read warehouse state `live`, or from the target's `synced_state` checked against the warehouse first; overrides the target's `plan_from`. See [Planning from synced state](/docs/concepts/project-configuration#planning-from-synced-state) | diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index 1a302e0722..034b17da7b 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -46,7 +46,8 @@ executable = "/usr/local/bin/sqb" | Section | Keys | | --- | --- | | `[server]` | `host` (default `127.0.0.1`), `port` (`8000`), `database_env` (`SQLBUILD_CONTROL_DATABASE_URL`), `password_origin`, `default_role` (`none`), `scheduler` (`true`), `attention_snooze` (`"24h"`); see [Acknowledge attention items](#acknowledge-attention-items) | -| `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`; see [Set retention](#set-retention) | +| `[retention]` | `statistics_days`, `audit_days`, `snapshot_count`, `run_log_days`, `run_log_count`, `state_history_versions`, `run_output_days`; see [Set retention](#set-retention) | +| `[output]` | `store` (an `output` folder beside a SQLite control database, or `~/.local/state/sqlbuild/output` with PostgreSQL), `max_bytes_per_run`; see [Keep run output](#keep-run-output) | | `[oidc]` | `origin`, `issuer`, `client_id`, `identities`, and optionally `client_secret_env`, `certificate_authority`, `groups_claim` and `group_roles` | | `[trusted_proxy]` | `origin`, and optionally `trusted_peers` (`127.0.0.1` and `::1`), `allowed_hosts`, `username_header` (`X-SQB-User`), `display_name_header`, `email_header`, `unknown_users` (`provision_viewer`), `proxy_logout_url` and `identities`; see [Sign in through a reverse proxy](#sign-in-through-a-reverse-proxy) | | `[[launchers.docker]]` | `location`, `target`, `server_url`, `max_workers`, `socket`, `location_container`, `executable`, and optional `run` and `pool_caps` tables; see [Limit worker containers](#limit-worker-containers) | @@ -98,12 +99,104 @@ adds a person from **People → Add person** with their sign-in name, a first pa them; they can change it after they sign in. Behind OIDC or a trusted proxy, people appear the first time they sign in instead, and the button isn't shown. +## Administer the server with sqb admin + +`sqb admin` works on the control database directly, on the server's host. Each command prints one +line on stderr that names what it did: + +```text +$ sqb admin create-location orders +Registered location orders (01a1fb47-0b3a-7631-ba35-e44d44d072f2) +``` + +| Command | On stdout | +| --- | --- | +| Issues a token or key: `issue-location-token`, `rotate-token`, `create-service-account`, `rotate-service-account` | Only the secret, once, so `VALUE="$(sqb admin ...)"` captures it. Nothing for an imported key | +| Reads: `location-work`, `list-service-accounts` | Plain rows, with no header | +| Everything else | Nothing | +| Any command with `--json` | Only the JSON result, with the secret in it when one was issued. The line on stderr is left out | + +When a script needs an ID, such as the new location's, use `--json`. `--verbose` also says when the +control store opens and is ready; without it, `sqb admin` says so only when opening takes more than +a second, as a migration can. Put both options after the command's name. A command whose output +can't be written exits with status 1 and says the change may already be committed. + +## Call the server from scripts with service accounts + +A service account lets a script, such as a deploy that republishes a project, call the server +with an API key under its own name. Add one in **People → Service accounts**, or on the server's +host: + +```bash +sqb admin create-service-account orders-deploy --role developer --description "Release pipeline" +``` + +The key is the only thing on stdout (`key` with `--json`), and the UI shows it once in a dialog. +Store it now, for example in your deploy's secret store: it isn't shown again, and the server keeps only a hash of it. The script +sends it in an `Authorization` header: + +```bash +curl -H "Authorization: Bearer $SQB_SERVICE_KEY" https://control.example.com/api/control/bootstrap +``` + +| Command | Does | +| --- | --- | +| `sqb admin create-service-account NAME --role ROLE` | Adds the account with a built-in role everywhere (`viewer`, `operator`, `developer` or `admin`) and prints its key. `--description` says what uses it. | +| `sqb admin rotate-service-account NAME` | Prints a new key. The replaced key stops now, or keeps working for `--overlap-minutes` (at most 1440) while you update the script. | +| `sqb admin disable-service-account NAME` | Refuses every key of the account at once. | +| `sqb admin enable-service-account NAME` | Accepts the same keys again. Rotate as well if a key may have leaked. | +| `sqb admin list-service-accounts` | Lists the accounts, their roles and the prefixes of their working keys, never the keys. | + +- **Keys.** A key starts with `sqbk_`, so you can recognise one in a script or a secret scanner. + The UI and the list show only its first characters, such as `sqbk_Q7m2xT`. +- **Rotating.** One old key works at a time: rotating again stops a key that is still in its + overlap. **Stop now** in a key's menu stops any key at once, the current one included; the + account then has no working key until you rotate. +- **Importing a key.** To recreate a control store with the same key, pass + `--key-from-env VAR` to `create-service-account`, with the key in the environment variable `VAR`. + It must start with `sqbk_` and have at least 32 more characters, without spaces. Generate it + randomly, for example `sqbk_` and 40 random letters and digits: SQLBuild can't tell a guessable key + from a strong one, so an imported key is only as strong as you make it. The command then doesn't print the + key. Only the CLI imports keys; the UI always makes a new one. +- **Any address.** A keyed request is accepted on whatever address the server listens on, with any + `Host`, so a server behind a sign-in proxy can also listen on the network, such as + `host = "0.0.0.0"`, for scripts. The proxy's username header is still trusted only from + `trusted_peers`, so a direct request can't sign in as a person. +- **TLS.** `sqb server` serves plain HTTP, and a key sent over plain HTTP crosses the network + unencrypted. Terminate TLS in front of any network listener, as in + [Serve over HTTPS](#serve-over-https), and give scripts its `https://` URL. The server warns at + start-up when it accepts keys on an address other than loopback without an `https://` origin. +- **Without people's sign-in.** On a server with no `password_origin`, `[oidc]` or + `[trusted_proxy]`, service keys are the only way to call its person API. Its sign-in page and + `sqb login` say so instead of asking for a password, and Settings shows the sign-in as + service account keys only. +- **Roles.** A service account holds its built-in role everywhere and doesn't get `default_role`. + That role decides what its key may do, as a person's does: an `admin` key can also manage service + accounts and roles, though it can't remove or disable the last admin who is a person. + In the UI, changing it needs `role.assign`. +- **No sign-in.** A service account has no password, browser session or `sqb login`, and a + `[trusted_proxy.identities]` binding to one is refused. +- **Audit.** Its actions appear in the audit log under its name. A request with a key that the + account no longer accepts, because the account is disabled or the key was stopped or rotated + away, is refused and recorded as `service_account.key_refused`, at most once a minute per key. +- **Last used.** The Service accounts tab shows when each key last made a request that wasn't + refused. + +| Action in the UI | Needs | +| --- | --- | +| See service accounts | `user.manage` or `role.assign` | +| Add a service account | `user.manage` and `role.assign` | +| Rotate, stop a key, disable or enable | `user.manage` | +| Change the role | `role.assign` | + ## Sign in through a reverse proxy A reverse proxy such as Apache or nginx can sign people in and tell the server who they are in a request header. The server trusts that header only on requests whose socket peer is listed in `trusted_peers`, so it never trusts a header that a browser sends straight to the server. With the -proxy on the same host, bind the server to loopback so that only local processes reach it: +proxy on the same host, bind the server to loopback so that only local processes reach it, or +listen on the network as well when [service accounts](#call-the-server-from-scripts-with-service-accounts) +call it from other hosts: ```toml [server] @@ -181,7 +274,8 @@ ProxyPassReverse "/" "http://127.0.0.1:8000/" - **The CLI.** `sqb login` still needs an `https://` server URL, so that its session token never crosses the network unencrypted. - **Locations and workers.** They use bearer tokens, not the proxy. On the server's own host, give - them `http://127.0.0.1:8000` so their tokens stay on loopback. + them `http://127.0.0.1:8000` so their tokens stay on loopback. Service accounts call with their + keys too, directly or through the proxy. - **Streaming.** The live-update feed sends `Cache-Control: no-cache, no-transform`, which stops `mod_deflate` from compressing it, and `X-Accel-Buffering: no`. It sends a keep-alive comment every 15 seconds, well within Apache's default 60-second `Timeout`. Long work, such as planning a @@ -323,18 +417,20 @@ afterwards, so back it up before you upgrade (see runs recorded since the upgrade are lost. A run stays pinned to the snapshot it started on, and a snapshot an earlier release published can -hold job definitions this release no longer reads, which fail with -`` jobs: unknown field `source`, expected `limit` ``. Upgrade in this order: +hold job definitions this release no longer reads. Upgrade in this order: -1. Pause every schedule and sensor, and start no manual runs. Keep the scheduler running: it - launches queued runs and advances group runs. +1. Pause every schedule and sensor, and start no manual runs. Keep the scheduler running through + step 2: it launches queued runs and advances group runs. 2. Let queued and running runs finish, or cancel them. -3. Upgrade the server. -4. Upgrade and restart every location, so each publishes its project again with the new release. -5. Once every location has published again, resume schedules and sensors. +3. Stop every server process and every separate `sqb scheduler` on the control database before the + new release starts, or migrates the database with `sqb server migrate` or `sqb admin`. +4. Start the servers and schedulers again on the new release. +5. Upgrade and restart every location, so each publishes its project again with the new release. +6. Once every location has published again, resume schedules and sensors. -Until a location has published again, its job pages, group runs and ad hoc runs fail, a group's -schedule or sensor stops the scheduler, and a job run that fails can't record its failure. +Until a location whose snapshot this release can't read has published again, its job pages, group +runs and ad hoc runs fail, and a schedule or sensor that starts a group is skipped and tried again +every minute. A failed job run on such a snapshot isn't retried. To see what an upgrade changes before you start the server, run the new release with `--dry-run`: @@ -403,6 +499,7 @@ snapshot_count = 20 run_log_days = 7 run_log_count = 100 state_history_versions = 10 +run_output_days = 7 ``` | Data | `[retention]` key | Option | Default | Range | @@ -413,6 +510,7 @@ state_history_versions = 10 | Logs of finished runs | `run_log_days` | `--run-log-retention-days` | `14` | `1`–`65535` | | Finished runs per location and target that keep their logs | `run_log_count` | `--run-log-retention-count` | `200` | `1`–`65535` | | Builds and check results kept for each node | `state_history_versions` | `--state-history-retention-versions` | `5` on SQLite, `20` on PostgreSQL | `1`–`65535` | +| Output that finished runs printed | `run_output_days` | None | `run_log_days` | `1`–`65535` | | Skipped and covered schedule ticks | None | None | 30 days | Fixed | Statistics samples older than the horizon disappear from statistics reads at once and are then @@ -469,6 +567,79 @@ An invalid value stops the server before it opens the control database. Servers control database delete at the shortest horizon among them and count only their own audit webhook, so give them the same values and webhook. +## Keep run output + +Everything a run prints goes to the server's output store, filed under the node that printed it. +Output printed outside any node, such as the worker's own messages, is filed under `run`. The +store keeps each node's stdout and stderr in zstd-compressed files of a few MB. The control +database keeps only a small index: where each node's lines are, and which lines look like errors +or warnings. A run that prints gigabytes does not grow the control database. + +Set the store in the `[output]` section of `server.toml`: + +```toml +[output] +store = "file:///var/lib/sqlbuild/output" +max_bytes_per_run = "20GB" +``` + +- `store` is a local folder, `file:///path`, or an S3 prefix, `s3://bucket/prefix`. By default it + is an `output` folder beside a SQLite control database. With PostgreSQL it is + `~/.local/state/sqlbuild/output` of the user that runs the server, or `sqlbuild/output` in + `XDG_STATE_HOME` when that is an absolute path, whichever directory the server starts in. In the + server image that is `/home/sqlbuild/.local/state/sqlbuild/output`. + [`sqb dev`](/docs/cli/dev/) keeps its output in `.sqlbuild/output` with its default control store. + With `--control-store-url` it uses an `output` folder beside that SQLite store, or the same folder + as above for PostgreSQL. +- `~` is `HOME` (`USERPROFILE` on Windows), or the account's home directory when that is unset. +- Servers on different control databases under the same user, including a server on a cloned + database, should each set their own `store` folder, or one's retention can delete another's + output. +- A local folder must be on a persistent volume, not inside the server's container, or recreating + the container loses every run's output. `compose.yml` and the Podman Quadlet example mount a named + volume at `/home/sqlbuild/.local/state/sqlbuild/output`. If you set another folder, mount a + volume there that user 10001 can write to. +- Use an S3 prefix when several servers share one control database, or when a replacement server + can't mount the same volume. The server reads AWS credentials from the standard AWS environment + variables or from the role it runs under. +- `max_bytes_per_run` is a number of bytes or text such as `"500MB"` or `"2GiB"`. Past it a run + keeps its first half and its newest half, and the lines in between are counted where they were + left out. By default a run keeps all of its output. + +If the service user's home can't be written, as with systemd's `DynamicUser=`, give the server a +state folder in its unit. Output then goes to `/var/lib/sqlbuild/sqlbuild/output`: + +```ini +[Service] +StateDirectory=sqlbuild +Environment=XDG_STATE_HOME=/var/lib/sqlbuild +``` + +The server prints `Run output store: ...` when it starts, with a local folder as an absolute path. + +Reading a run's output needs `view.evidence` on every node the run selected. The security audit +records each search and download. The run page reads a run's lines and index every few seconds while +it follows the run, so each server records those reads once in 10 minutes for each person, run and +kind of read. People read a node's output with its stdout and stderr lines in the +order printed, or one stream of it, or the whole run's output with each line's node. They page +forwards and backwards, read the last lines, fold runs of similar lines, search in either direction, +jump to error and warning lines, or download a node's output whole. No read loads a whole log at +once. + +A worker sends what it prints in batches of about 4 MB, or every 2 seconds. When a node prints +faster than the worker can send, the node waits for the worker. If the server stops accepting +output for 30 seconds, the worker drops what it cannot send. It prints +`Run output: N bytes of run output were not stored` to its log, with the reason, and adds the same +warning to the run. + +A finished run's output is deleted `run_output_days` after the run ended; the run, its node results +and the lines its nodes logged with `ctx.log` stay. + +Upgrade the server before its workers. An older server keeps none of a newer worker's output, and +the worker's log says `the control server is older than this worker and does not accept run output; +upgrade the server before its workers`. A node that logs with `ctx.log` fails on an older server +with the same request to upgrade it. + ## Grant roles to OIDC groups (beta) With OIDC sign-in, members of an identity-provider group can get a role without a per-person @@ -713,7 +884,7 @@ delay_seconds = 600 | --- | --- | --- | --- | | `owner` | Any non-blank text | None | Shown on the job's page and in the job list | | `overlap` | `queue` or `skip` | `queue` | With `skip`, a schedule tick or sensor request that arrives while a run of the job is queued or running starts no run | -| `retry` | `attempts` from 2 to 11, `delay_seconds` from 0 to 86400 | None | A failed or partial run reruns its failed and skipped nodes after the delay, until it succeeds or has run `attempts` times in all | +| `retry` | `attempts` from 2 to 11, `delay_seconds` from 0 to 86400 | None | A failed or partial run nobody cancelled reruns its failed, cancelled and skipped nodes, and those it never reached, after the delay, until it succeeds or has run `attempts` times in all | A skipped tick shows as **skipped** in the trigger's tick log, with the run it yielded to, and creates no run. A sensor tick lists the requests it skipped the same way. @@ -735,7 +906,7 @@ Details: again after `delay_seconds`, inside the same group run, and the jobs that depend on it wait instead of skipping. The group keeps its pool slots meanwhile. - A group's own `[retry]` is a final sweep: after the group run ends `failed` or `partial`, it - queues one new linked rerun of the group's failed and skipped nodes. + queues one new linked rerun of the group's failed, cancelled and skipped nodes, and those it never reached. - So a retry of a whole run, a job's or a group's, is a new linked run, and a retry of a member stays inside its group run. - Sensors and alerts see a member's final attempt only. The group run's timeline shows each retry, @@ -1021,7 +1192,8 @@ permissions = ["view.evidence"] | No matching nodes | Publication succeeds with a warning; the grant gives nothing | | Permissions | Any non-administrative action; `user.manage`, `role.assign` and `audit.view` are rejected | | Runs | `job.run`, `run.rerun` and `run.rewrite_history` need the permission on every node the run writes; an [ad-hoc command](#run-ad-hoc-commands) needs `run.adhoc` and its flags' permissions on every node it selects; a priority above 0 also needs `run.prioritise` | -| Triggers | `trigger.toggle` (on, off) and `sensor.reset_cursor` (start over, skip an event) need the permission on every node a schedule's job writes, and for a sensor on every node of the target | +| Republish a location | `location.republish` on the location and target; reading its discovered sets back needs `view` | +| Triggers | `trigger.toggle` (on, off) and `sensor.reset_cursor` (start over, skip an event) need the permission on every node a schedule's job writes. A sensor needs it on every node of the target, as does pausing or resuming a schedule whose job can't be read | | Listings | The catalog, statistics, providers and run list need `view` on every node of the current publication; partial coverage is denied, not filtered | | Several roles | Grants add up across a person's roles | diff --git a/website/src/content/docs/docs/concepts/models/hooks/python.mdx b/website/src/content/docs/docs/concepts/models/hooks/python.mdx index 01547d6380..e7f8c371cf 100644 --- a/website/src/content/docs/docs/concepts/models/hooks/python.mdx +++ b/website/src/content/docs/docs/concepts/models/hooks/python.mdx @@ -22,7 +22,7 @@ from sqlbuild.hooks import hook @hook def notify_complete(ctx, channel="#data-builds"): """Notify complete.""" - ctx.log( + ctx.log.info( f"Notify {channel}: " f"{ctx.model_name} completed during {ctx.phase}" ) @@ -122,7 +122,7 @@ Python hooks declare a `HookContext` parameter named `ctx`, `context`, `_ctx`, o | `ctx.connection` | Live connection | | `ctx.execute_sql(sql)` | Execute SQL | | `ctx.query(sql)` | Execute SQL and return rows | -| `ctx.log(message)` | Write run output | +| `ctx.log.info(message)`, `ctx.log.warning(message)`, `ctx.log.error(message)` | Log a line at that level; it shows with the run's events, while anything the hook prints stays its output | | `ctx.skip(reason="...", mode="soft")` | Return a soft or hard skip result; arguments are keyword-only | | `ctx.providers` | Access discovered [providers](/docs/concepts/python-nodes/providers) | diff --git a/website/src/content/docs/docs/concepts/observability/recall.mdx b/website/src/content/docs/docs/concepts/observability/recall.mdx index 528720c34b..a684e3a26f 100644 --- a/website/src/content/docs/docs/concepts/observability/recall.mdx +++ b/website/src/content/docs/docs/concepts/observability/recall.mdx @@ -132,6 +132,14 @@ can contain sensitive SQL, output and audit evidence. | `abandoned` | Its heartbeats stopped without an end: the process died, for example after SIGKILL or running out of memory | | `unknown` | Recall has neither an end nor a heartbeat for it | +Ctrl-C stops a command at any point, also at a prompt such as a warehouse sign-in: it cancels the +statements it is running, cleans up, prints `error: interrupted (Ctrl+C)` and exits with code 130. +When nothing can unwind it, such as a driver that asks again or reads on another thread, it is +ended after 0.6 seconds if it has run no statement or is still opening the connection it was +waiting for. While [discovered steps](/docs/concepts/python-nodes/discovered-nodes) run, their +own cancel ends it instead, within 5 seconds. Otherwise press Ctrl-C again to end it. A command ended that way can't record its +end, so Recall shows it `abandoned`. + A command stopped by SIGTERM, as an orchestrator stops a job, ends the way Ctrl-C ends it: it cancels the statements it is running, records its real end time, its output and exit code 143, prints `error: terminated by SIGTERM`, and exits with code 143. It does this also when it was diff --git a/website/src/content/docs/docs/concepts/observability/sinks.mdx b/website/src/content/docs/docs/concepts/observability/sinks.mdx index d7c6ea84f0..b1b4e2bd07 100644 --- a/website/src/content/docs/docs/concepts/observability/sinks.mdx +++ b/website/src/content/docs/docs/concepts/observability/sinks.mdx @@ -82,7 +82,8 @@ under `[sinks.lifecycle]`, not per named sink. `"0s"` drops anything still queue final quarter of the budget is reserved for run and invocation outcomes: when it begins, other queued events are dropped and counted so the outcomes still arrive. The setting does not change the one-second timeout for each sink call. A sink call still running when the budget ends gets up to that one second to return before providers are torn down; teardown -always runs on the command's own thread. +always runs on the command's own thread. A cancel that leaves a step running skips teardown, +as described under [Providers](/docs/concepts/python-nodes/providers#lifecycle). ```toml [sinks.lifecycle] diff --git a/website/src/content/docs/docs/concepts/orchestration.mdx b/website/src/content/docs/docs/concepts/orchestration.mdx index bb109c61de..39175d912d 100644 --- a/website/src/content/docs/docs/concepts/orchestration.mdx +++ b/website/src/content/docs/docs/concepts/orchestration.mdx @@ -275,7 +275,7 @@ Pass `name="..."` to choose another name, which must also end in `_sensor`. | --- | --- | | `run_event(job="...", kinds=[...])` | Each run of the job or group that ends with one of `kinds`, optionally only when `executed_successfully` nodes ran and succeeded | | `node_event(select="...", kinds=[...])` | Each success, failure or recovery of the selected nodes in any run | -| `check_event(select="...", kinds=[...])` | Each check, audit or SQL test on the selected nodes that fails or warns inside a job or job group run, whatever the run's outcome; ad-hoc `sqb test` and `sqb audit` runs don't count | +| `check_event(select="...", kinds=[...])` | Each check, audit or SQL test on the selected nodes that fails or warns inside a job, job group or manual build run, whatever the run's outcome; standalone `sqb test` and `sqb audit` runs don't count | | `source_new_data(select="...")` | Each new version of the selected sources | | `source_stale(select="...", after_seconds=...)` | Each source version older than `after_seconds` | | `platform_event(kinds=[...])` | Each server event of `kinds`, such as an overdue tick or a failed run | @@ -284,8 +284,9 @@ Pass `name="..."` to choose another name, which must also end in `_sensor`. `kinds` take the enums `RunEventKind`, `NodeEventKind`, `CheckEventKind` and `PlatformEventKind` from `sqlbuild.orchestration`. `RunEventKind` has `SUCCESS`, `WARN`, `PARTIAL`, `FAILED`, `CANCELLED`, `SKIPPED` (a member its group did not run) and `COMPLETED` for any of them. -`CheckEventKind` has `FAILED` and `WARN`. `check_event` covers checks inside job runs, not -`sqb test` or `sqb scenario test`. +`CheckEventKind` has `FAILED` and `WARN`. `check_event` covers checks inside job runs and manual +builds, such as one started from the Plan page, where the event's `job` is `None`. It doesn't +cover standalone `sqb test` or `sqb audit` runs, or `sqb scenario test`. ### What the function gets and returns diff --git a/website/src/content/docs/docs/concepts/python-nodes/assets.mdx b/website/src/content/docs/docs/concepts/python-nodes/assets.mdx index 908cc89136..214456a4a1 100644 --- a/website/src/content/docs/docs/concepts/python-nodes/assets.mdx +++ b/website/src/content/docs/docs/concepts/python-nodes/assets.mdx @@ -187,6 +187,7 @@ The default is no retry. Set `retry_on` explicitly rather than relying on the br | `description` | Docs (defaults to docstring) | | `meta` | Freeform JSON metadata | | `retry` | A `RetryPolicy` | +| `for_each` | A `@discover` function; the asset runs once per item it returns. See [Discovered nodes](/docs/concepts/python-nodes/discovered-nodes) | ## Running assets diff --git a/website/src/content/docs/docs/concepts/python-nodes/discovered-nodes.mdx b/website/src/content/docs/docs/concepts/python-nodes/discovered-nodes.mdx new file mode 100644 index 0000000000..c56ddd6085 --- /dev/null +++ b/website/src/content/docs/docs/concepts/python-nodes/discovered-nodes.mdx @@ -0,0 +1,143 @@ +--- +title: "Discovered nodes" +description: "Run a Python asset once per item an external system lists, with @discover and @asset(for_each=...)." +--- + +A discover function asks an external system which items exist, and an asset with `for_each` runs once per item. The location calls the function when it publishes and saves its result in the snapshot, so every run executes exactly the nodes it published. + +```python +# python/fulfilment/nodes.py +from sqlbuild.assets import AssetContext, asset +from sqlbuild.discovery import Discovered, Item, discover +from sqlbuild.refs import model + + +@discover(check_every="15m") +def fulfilment_plan(warehouse_api) -> Discovered: + """Steps of today's fulfilment plan.""" + plan = warehouse_api.todays_plan() + return Discovered( + items=[ + Item(id=step["id"], depends_on=step["after"], args={"region": step["region"]}) + for step in plan["steps"] + ], + tags={"plan_version": plan["version"]}, + max_parallel=4, + ) + + +@asset(for_each=fulfilment_plan, depends_on=model("orders")) +def fulfil(ctx: AssetContext, region: str) -> None: + """Run one step of the plan.""" + ctx.log.info(f"step {ctx.discovered.item} for {region}, plan {ctx.discovered.tags['plan_version']}") +``` + +With steps `pick`, `pack` and `ship`, where each waits on the one before, the graph is +`orders → fulfil[pick] → fulfil[pack] → fulfil[ship]`. + +## Declaring a discovered set + +- **`@discover`** marks a project function under `python/` that returns `Discovered`. Providers are injected by parameter name, as for any Python node. Pass `name=` to name the set something other than the function, and `check_every=` to have the location check it for changes (see [When discovery runs](#when-discovery-runs)). +- **`Discovered`** is the only return form: `items`, plus optional set-wide `tags` and `max_parallel`. +- **`Item`** has an `id`, a `depends_on` and `args`. + - `id` is unique in the set, at most 200 characters, and uses only letters, digits and `_ . : -`. + - `depends_on` lists the IDs of other items of the set. It may also name project nodes with `model()`, `source()`, `seed()`, `job()` or `tag()`. + - `args` fill the asset function's own parameters, other than its context and providers. +- **`@asset(for_each=...)`** names the discover function. It is an ordinary Python asset: it takes every other `@asset` parameter, and one discover function may feed several assets. Each item becomes one node per asset, named `[]`. + +A set fails as a whole, and keeps its last good items, when: + +- the function raises or returns something other than `Discovered`; +- it returns no items, as an empty answer from a remote system is far more often a fault than a plan with no steps; +- an ID is invalid or repeated, an item depends on an ID outside the set, or items depend on each other in a cycle; +- an item depends on a model, source, seed or job the project doesn't have; +- an item's `args` name a parameter the asset doesn't have, or leave a parameter without a default unset; +- `args` or `tags` aren't JSON data. + +## Dependencies + +- The asset's own `depends_on` attaches to the set's **roots**, the items that wait on no other item of the set. Every other item waits on a root, so ordering is exact. +- Other nodes depend on the set with `job()` or `tag()`, which resolve to its last nodes. Nothing needs to name an item. + +## In a node + +| Attribute | Description | +|-----------|-------------| +| `ctx.discovered.item` | The item ID this node runs for | +| `ctx.discovered.set` | The discover function's name | +| `ctx.discovered.tags` | The set's tags, as saved at publish | +| `ctx.root_run_id` | The server's run ID of the first run in the rerun chain. Reruns and automatic retries keep it, so an external pipeline can keep one identity across them. Don't compare it with `ctx.run_id`, which is the worker's own ID and differs on every run. Outside a worker it is the local run's ID | + +`ctx.discovered` is `None` for an asset without `for_each`. + +## Selecting discovered nodes + +| Selector | Selects | +|----------|---------| +| `fulfil[pack]` | The one node of item `pack` | +| `+fulfil[ship]` | Item `ship` and every item and node before it | +| `fulfil` or `asset:fulfil` | Every node of the asset, whatever the items are | + +Jobs select the asset by name, so job files don't change when the items do. + +## Running items in parallel + +`max_parallel` caps how many of the set's nodes run at once within one run. Assets fed by the same +discover function share the cap. Without it, or with `1`, the items run one at a time. It is +independent of `concurrency`, and every other asset still runs one at a time. + +- **Providers used by these steps must be thread-safe.** The steps run on threads of one process and share the provider instances. +- **A step can't install signal handlers,** as Python allows that only on the main thread. +- **Each running step has its own warehouse connection.** An in-memory DuckDB, MotherDuck or SQLite database belongs to one connection, so on those targets items run one at a time, whatever `max_parallel` is. Use a database file to run them in parallel. +- **Local output can interleave.** A worker still files each line under the node that printed it. +- **SQL pauses while items run.** New SQL, and steps waiting on SQL, start again once the running items have finished. +- **A cancel starts no more steps.** It cancels running statements and keeps finished steps succeeded. SQLBuild can't stop other Python code, so it waits 5 seconds for those steps, then records them cancelled and exits. It doesn't tear down providers that such a step may still be using: their `teardown` doesn't run. Work a step started on a remote system may outlive the cancel. + +## When discovery runs + +Only a location, including `sqb dev`, calls discover functions. Every other compile uses the result saved in the snapshot, like a lockfile: + +| Trigger | What happens | +|---------|--------------| +| The location starts (every deploy or restart) | Every discover function runs | +| `r` in `sqb dev` | Every discover function runs, and the location publishes | +| A [republish](/docs/cli/location#republish), from the UI, the CLI or the API | Every discover function runs, and the location publishes | +| A saved project file | The location publishes and reuses the saved sets; a discover function runs again only when its own module changed | +| `check_every` | The location calls that function without publishing. When the result differs from the saved set, it publishes with the new result | + +- `check_every` takes amounts in `d`, `h`, `m` and `s`, largest unit first, such as `15m` or `1h30m`, and at least a minute. Without it, the set is checked only when the location publishes. +- A check doesn't hold up the location. Once a publish, republish or other request waits for it, the check has 10 seconds to finish. After that the location restarts its interpreter and serves the request, and the set is checked again when it is next due. +- Runs always execute the nodes of the snapshot they started on. Workers, reruns and the plan page never call discover functions. +- `sqb dev`'s ready card shows the sets, for example `Discovered fulfilment_plan 3 items`. + +## When discovery fails + +- **A set fails on its own.** It keeps its last good items, the location's health shows **Discovery failed** with the set and its error, and everything else publishes normally. A location that restarts reads the last good items from the server's current snapshot. +- **Last good items that name a model, source, seed or job the project no longer has** aren't kept. That covers a publish that reuses a set after the model it names was renamed or removed: the set fails with an error naming the item and the missing node, and compiles as its placeholder until it's discovered again. +- **An item that depends on a `tag()` no node carries** still fails the whole publish, not only its set: tags are known only once the project compiles. The location keeps its current snapshot and reports the error. +- **A set that never succeeded** compiles as its **placeholder node**, `[*]`. Its `job()` and `tag()` dependants stay valid. A run that reaches it fails that node with `never discovered: `, and its downstream nodes are skipped. + +## Outside a location + +`sqb compile`, `sqb plan` and `sqb build` never call discover functions by default. Each `for_each` asset compiles as its placeholder, `fulfil[*]`, so lineage and `job()`/`tag()` dependencies stay valid. + +Selecting a placeholder to run fails: + +```text +error[S000]: fulfil is discovered at publish; run it from a location or `sqb dev`, or pass --discover +``` + +Pass `--discover` to run the discover functions for that one command, with the selected target's providers: + +```bash +sqb build --discover --select +fulfil[ship] +``` + +Nothing is written to disk. If a discover function fails under `--discover`, the command stops with its error. + +## Details + +- Discovered nodes are Python assets only; discovery returns data, never code. +- To create several sets from one source, use a [factory](/docs/concepts/python-nodes/factories) that returns one discover function and one asset per set. +- A node's identity includes its item's `args` and the set's `tags`, so a changed argument shows in the plan like a code change. +- Workers compile the saved sets of the run's snapshot, so a run is unaffected by changes in the external system after it was published. diff --git a/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx b/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx index 16ff8f98c4..ca5d84c77e 100644 --- a/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx +++ b/website/src/content/docs/docs/concepts/python-nodes/loaders.mdx @@ -251,7 +251,7 @@ Every loader function receives a `LoaderContext` as its first argument. It provi |--------|-------------| | `execute_sql(sql)` | Execute a SQL statement against the connection | | `query(sql)` | Execute a SQL query and return the cursor | -| `log(message)` | Log a message to the execution lifecycle output | +| `log.info(message)`, `log.warning(message)`, `log.error(message)` | Log a line at that level; it shows with the run's events, while anything the loader prints stays its output | | `qualify_name(name)` | Return a fully-qualified relation name in the destination database/schema | | `skip(reason, mode=...)` | Skip this loader. `mode` is `"soft"` (default, skip only this loader) or `"hard"` (also block dependents) | | `result(payload=, metadata=, materialized=)` | Return a structured result for a self-managed loader | diff --git a/website/src/content/docs/docs/concepts/python-nodes/overview.mdx b/website/src/content/docs/docs/concepts/python-nodes/overview.mdx index 88933a2e4b..cae0dd3dd7 100644 --- a/website/src/content/docs/docs/concepts/python-nodes/overview.mdx +++ b/website/src/content/docs/docs/concepts/python-nodes/overview.mdx @@ -136,13 +136,13 @@ Each node receives a context object as its first argument (`AssetContext`, `Chec | Helper | Description | |--------|-------------| -| `ctx.run_id` | Unique identifier for this run | +| `ctx.run_id` | Unique identifier for this run; in a worker, the worker's own ID rather than the server's run ID | | `ctx.target` | Active target name | | `ctx.target_config` | The active target's database and schemas, as SQLBuild resolves them (see [Target settings](#target-settings)) | | `ctx.vars` | Project variables | | `ctx.is_reload` | `True` when `--reload` was passed | | `ctx.adapter` / `ctx.connection` | Adapter and live connection | -| `ctx.log(message)` | Log to the run output | +| `ctx.log.info(message)`, `ctx.log.warning(message)`, `ctx.log.error(message)` | Log a line at that level; it shows with the run's events, while anything the node prints stays its output | | `ctx.query(sql)` / `ctx.execute_sql(sql)` | Run SQL on the connection | | `ctx.qualify_name(name)` | Qualify a relation name | | `ctx.relation(ref)` | Resolve a declared `model()`/`source()` reference to a relation | @@ -150,7 +150,7 @@ Each node receives a context object as its first argument (`AssetContext`, `Chec | `ctx.results_of(node_fn, limit=N)` | Read the last N successful results of an upstream node, newest first | | `ctx.providers` | Access discovered [providers](/docs/concepts/python-nodes/providers) by name | -Asset contexts add `ctx.result(...)` and `ctx.skip(...)`. Check contexts add `ctx.pass_(...)`, `ctx.fail(...)`, and `ctx.warn(...)`. +Asset contexts add `ctx.result(...)`, `ctx.skip(...)`, `ctx.root_run_id` and `ctx.discovered` (see [Discovered nodes](/docs/concepts/python-nodes/discovered-nodes#in-a-node)). Check contexts add `ctx.pass_(...)`, `ctx.fail(...)`, and `ctx.warn(...)`. Providers can also be injected directly as function parameters by name. See [Providers](/docs/concepts/python-nodes/providers) for details. diff --git a/website/src/content/docs/docs/concepts/python-nodes/providers.mdx b/website/src/content/docs/docs/concepts/python-nodes/providers.mdx index 80a6f44915..9a26bea5fb 100644 --- a/website/src/content/docs/docs/concepts/python-nodes/providers.mdx +++ b/website/src/content/docs/docs/concepts/python-nodes/providers.mdx @@ -134,7 +134,7 @@ Providers follow a lazy setup, reverse-teardown lifecycle scoped to the command 1. **Discovery** - on compile, SQLBuild discovers all `Provider` subclasses under `providers/` and validates their settings (from environment variables or field defaults). Missing [secrets](#secrets) follow the command's rules. 2. **Lazy setup** - the first time a provider is accessed during a build, SQLBuild reads its settings and calls `setup(ctx)`. Providers that are never used are never set up. -3. **Teardown** - after the command completes, `teardown()` is called on all providers that were set up, in reverse setup order. Teardown runs even if the build failed. +3. **Teardown** - after the command completes, `teardown()` is called on all providers that were set up, in reverse setup order. Teardown runs even if the build failed. The exception is a cancel that leaves a step with `max_parallel` running after 5 seconds: providers are then not torn down, as that step may still use them (see [Running items in parallel](/docs/concepts/python-nodes/discovered-nodes#running-items-in-parallel)). ```python class WarehouseClient(Provider): @@ -216,6 +216,11 @@ class SlackAlerts(Provider): slack_webhook_url: SecretStr # reads SLACK_WEBHOOK_URL ``` +Declare every secret a provider needs as a required field. Don't declare it as optional, such as +`api_key: SecretStr | None = None`, and fail in `setup` or in a method when it is empty: SQLBuild +can't know that such a field is required, so none of the checks below see it, and a run fails only +when its node first uses the provider, after connecting and planning. + SQLBuild looks for each variable in the environment and then in the project's [env file](/docs/concepts/project-configuration#env-file). @@ -231,9 +236,12 @@ SQLBuild looks for each variable in the environment and then in the project's ```text $ sqb compile error[D012]: provider 'slack_alerts' (providers/slack_alerts/provider.py) is missing secret SLACK_WEBHOOK_URL - = help: set SLACK_WEBHOOK_URL, or pass --allow-missing-secrets where secrets aren't available + = help: set SLACK_WEBHOOK_URL in this shell or in .env, or pass --allow-missing-secrets where secrets aren't available ``` +The help names the env file the selected target loads, and suggests the flag only on the commands +that take it. + A run names each variable, the nodes that use the provider and the selected nodes that read them, and where it looked: @@ -242,7 +250,7 @@ $ sqb build --select +partner_orders_report error[D012]: selected nodes need secrets that are missing from the environment and from .env: partner_api PARTNER_API_TOKEN (raw_partner_orders; read by partner_orders_report) nothing was run - = help: set each variable in this shell or the project's env file, or narrow the selection + = help: set each variable in this shell or in .env, or narrow the selection ``` Run [`sqb debug`](/docs/cli/debug/) to see which secrets this machine has. @@ -297,7 +305,9 @@ In `--json`, `cant_run` names the sink under `sinks`. Nobody looks at a plan for a schedule or sensor, so its run checks the same thing on the worker, before compiling a plan or connecting. Each node that uses the provider fails with `D012`, the nodes that read it are skipped, and the run page shows **Couldn't run** with the provider, its variables -and the fix: set them in the location's environment or its env file, and restart the location. +and the fix: set them in the location's env file, or in the environment the location was started +with, then restart the location. Under `sqb dev`, `r` is enough after editing the env file; a +change to the environment needs `sqb dev` to be started again. The location reports the providers missing secrets each time it publishes. Its page lists them with their variables, fields and the nodes that can't run, and the Overview lists the problem for that diff --git a/website/src/sidebar.json b/website/src/sidebar.json index 34389fe9b9..ca0bb1d152 100644 --- a/website/src/sidebar.json +++ b/website/src/sidebar.json @@ -179,6 +179,7 @@ "docs/concepts/python-nodes/assets", "docs/concepts/python-nodes/checks", "docs/concepts/python-nodes/factories", + "docs/concepts/python-nodes/discovered-nodes", "docs/concepts/python-nodes/providers", "docs/concepts/python-nodes/sql-references" ]