micromegas_analytics/lakehouse/ownership_rewrite.rs
1//! `OwnershipRewrite` -- the row-level filter.
2//!
3//! An `AnalyzerRule` that injects an audience-filtering predicate into every
4//! `MaterializedView`-backed `TableScan` a query plan touches, based on the caller's `ReadScope`
5//! (`read_scope.rs`) and [`crate::lakehouse::read_scope::IsolationConfig`]'s
6//! `public_view_sets` (a deployment setting, with `MICROMEGAS_PUBLIC_VIEW_SETS` as its env fallback).
7//!
8//! ## `ReadScope::All` is a true no-op
9//!
10//! `ReadScope::All` is the internal/maintenance marker -- never the output of a real `ReadPolicy`
11//! (see `read_scope.rs`). `analyze()` returns the plan unchanged when constructed with it, and
12//! `query.rs::make_session_context` does not even construct this rule for `ReadScope::All`
13//! callers, so their `ViewFactory` need not carry `processes`/`streams` either.
14//!
15//! ## The physical `audience` column
16//!
17//! `blocks`, `processes`, `streams`, `log_entries`, `measures`, `otel_histograms`, and `log_stats`
18//! each carry a physical `audience` column -- declared non-nullable on
19//! `blocks`/`log_entries`/`measures`/`otel_histograms`, and
20//! non-null by construction (though declared nullable in their inferred `SqlBatchView` schema) on
21//! `processes`/`streams`/`log_stats` -- extracted once from Postgres's own `audience` column at
22//! the `blocks` view's materialization (its own row's stamp) and propagated structurally into
23//! every downstream view. A DDL-defined materialized view carrying its own `audience` column
24//! (enforced at `CREATE` time, see `view_definition.rs`) joins this group too. Every view
25//! carrying an `audience` column is consequently filtered with a bare `Filter` on that column
26//! (the column-filter branch in the table below): no semi-join, no `property_get`, no
27//! per-process aggregate. `async_events`, `thread_spans`, `net_spans`, `otel_spans`, and `images`
28//! don't carry the column. They keep the `process_id`/`EXISTS` machinery below, which still
29//! resolves through `__processes__partitions`, but only for a scan that is *not* a guarded
30//! `view_instance(...)` -- see the skip rule in the Branch table below.
31//!
32//! ## One audience per row, not derived from the process (surviving branches only)
33//!
34//! `__processes__partitions` (the raw, un-merged `SqlBatchView` partitions `self.processes_source`
35//! scans) can carry more than one historical row per `process_id` -- the partition-level
36//! `GROUP BY` in `processes_view.rs`'s transform query only collapses rows *within* a partition,
37//! not across a long-lived process's entire history. Filtering the views carrying an `audience`
38//! column, DDL-defined ones included, one row at a time (the column-filter branch) is sound
39//! without any aggregate: every row now carries
40//! its own stamp from the moment it was written, so there is nothing to reconcile across rows of
41//! the same process. The one exception is a legacy, pre-v8 row with no `audience` column at all --
42//! `COALESCE` resolves that to the deployment default at read time. The `net_spans`/
43//! `otel_spans`/`images` semi-join branch and the `async_events`/`thread_spans` `EXISTS` branches
44//! still resolve through `per_process_audience` -- `Aggregate(GROUP BY process_id, MAX(audience)
45//! AS resolved_audience)` -- for a scan of those five that is *not* a guarded instance, since they
46//! have no `audience` column of their own to filter directly. A guarded instance skips the
47//! predicate entirely (see the Branch table below).
48//!
49//! ## Branch table
50//!
51//! Keyed on `MaterializedView::get_view().get_file_schema()`: whether it has an `audience` field,
52//! failing that whether it has a `process_id` field -- not on a hardcoded view-set list, so a
53//! future view set that gains either column falls into the matching branch automatically:
54//!
55//! | View set | Branch |
56//! |---|---|
57//! | `processes`, `streams`, `blocks`, `log_entries`, `measures`, `otel_histograms`, `log_stats`, and any DDL-defined view carrying an `audience` column | `column filter`: direct `audience IN (...)` filter on the view's own column (`audience IS NOT NULL` under `EveryAudience`) -- no join |
58//! | `net_spans`, `otel_spans`, `images`, `async_events`, `thread_spans`, scanned as a guarded, non-`'global'` `view_instance(...)` | `skip`: no predicate at all -- `MaterializedView::instance_is_audience_guarded()` reports `AudienceGuard::authorize_view_instance` already denies an unauthorized caller before any row is read, so the subquery predicates below would be redundant |
59//! | `net_spans`, `otel_spans`, `images`, not a guarded instance | `semi-join`: `process_id IN (subquery)` against `per_process_audience` (outer `process_id` cast to `Utf8`: it is `Dictionary(Int32, Utf8)` in these, and nothing coerces an uncorrelated `IN` subquery's join keys once `DecorrelatePredicateSubquery` turns it into a `LeftSemi` join -- the analyzer's own `TypeCoercion` has already run by the time this rule executes) |
60//! | `async_events`, not a guarded instance | no `process_id` column either -- `async_events EXISTS`: literal-valued `EXISTS`, keyed on `get_view_instance_id()` (the process_id string, canonicalized -- see `canonical_view_instance_id`) |
61//! | `thread_spans`, not a guarded instance | no `process_id` **or** `stream_id` column -- `thread_spans EXISTS`: two-hop literal `EXISTS`, through `streams` (`get_view_instance_id()` is the stream_id string, canonicalized the same way) |
62//! | anything in `public_view_sets` | `public`: no predicate at all -- checked before any of the above |
63//! | anything else | `analyze()` returns `Err` (`DataFusionError::Plan`) rather than silently leaving the scan unfiltered -- a future view set must add itself to this table, not fall through |
64//!
65//! Adding a new view set to a `ViewFactory` means adding it to this table too, and to the match
66//! arms in `OwnershipRewrite::predicate_for` below.
67//!
68//! ## No I/O in `analyze()`
69//!
70//! `in_subquery`/`exists` build uncorrelated subquery `Expr`s; `DecorrelatePredicateSubquery` (an
71//! optimizer, not analyzer, rule) turns them into joins later. `processes_source`/`streams_source`
72//! come from `MaterializedView::new(..., query_range: None)`, which is synchronous and does no I/O
73//! -- the actual `processes`/`streams` scans happen during normal execution, exactly like
74//! `TableScanRewrite`'s injected time filter.
75//!
76//! ## The `audience` column is server-written and authenticated
77//!
78//! `processes`, `streams`, and `blocks` are each stamped with their own `audience` column at
79//! write time, from the authenticated credential's `AuthContext.bound_audience`
80//! (`resolve_write_audience`), and a client can neither assert nor forge that stamp
81//! (`strip_reserved_properties` drops any client-supplied `micromegas.*` property, and there is
82//! no property to re-assert in the first place any more -- the stamp is a physical column, not a
83//! property). A credential carrying no bound audience resolves to the deployment default at the
84//! HTTP write edge and is stamped with it explicitly, the same as any other audience -- only a
85//! legacy, pre-v8 row keeps a NULL column, resolved to the deployment's
86//! `MICROMEGAS_DEFAULT_AUDIENCE` where the audience is *read* instead (see `crate::audience`'s
87//! module doc). Admin replication (`replication.rs`) now hard-fails on a missing `audience`
88//! column rather than ever writing a row with none. Registration
89//! (`insert_process`/`register_otel_process`) rejects a same-`process_id`, different-audience
90//! re-registration outright -- needed because the OTLP `process_id` derivation formula is public,
91//! so without this guard a credential could pre-register (via the native path) the exact
92//! `process_id` a victim audience's OTLP producer would later derive, silently exposing that
93//! audience's data to the squatter; this is a confidentiality gap, not merely an integrity one.
94//! The stream-side mirror, `check_stream_audience_conflict`, closes the equivalent
95//! re-pointed-credential gap for `streams`.
96//!
97//! **What remains open, tracked separately:**
98//! - **The five instance-only view sets** (`net_spans`, `otel_spans`, `images`, `async_events`,
99//! `thread_spans`) **and the per-process JIT `view_instance` path** still resolve their audience
100//! *label* through the owning process's/stream's row rather than a genuine per-row column of
101//! their own -- via the call-level guard's instance check (`AudienceGuard::authorize_view_instance`,
102//! `IdKind::ProcessOrStream`) for the guarded `view_instance(...)` scan every production caller
103//! takes, not by a predicate this rule injects (see the skip in the Branch table above). The
104//! cross-audience *injection* scenario (an attacker's block naming a victim's
105//! `process_id`/`stream_id`) is closed for both, as a side effect of the mismatch predicate on
106//! `blocks_view`'s own materialization -- except against a victim whose `processes`/`streams`
107//! row is a legacy, pre-v8 NULL-audience row (next bullet).
108//! - **The NULL-anchor window.** A `processes`/`streams` row registered before its ingestion
109//! binary supported per-row stamping keeps `audience = NULL` for its entire remaining life
110//! (rows are immutable, no backfill). The mismatch predicate's NULL-tolerant pass-through lets
111//! a mismatched block through unchecked against such a row for as long as it exists. This is
112//! an accepted, bounded limitation over already-public legacy data, bounded by the deploy-order
113//! requirement (every ingestion replica upgraded) and shrinking as legacy rows age out under
114//! retention.
115//!
116//! There is no in-product enforcement knob left for either surface; the mitigation is
117//! operational -- provision only audience-bound DB-backed ingestion credentials, and don't run
118//! ingestion with OIDC or `--disable-auth` alongside them -- see this stage's `CHANGELOG.md`
119//! entry.
120
121use super::{materialized_view::MaterializedView, read_scope::ReadScope};
122use datafusion::{
123 arrow::datatypes::{DataType, Field},
124 common::{Column, TableReference, tree_node::Transformed},
125 config::ConfigOptions,
126 datasource::DefaultTableSource,
127 error::DataFusionError,
128 functions_aggregate::min_max::max,
129 logical_expr::{Filter, LogicalPlan, LogicalPlanBuilder, TableSource},
130 optimizer::AnalyzerRule,
131 prelude::*,
132 scalar::ScalarValue,
133};
134use std::sync::Arc;
135use uuid::Uuid;
136
137/// Injects an audience predicate into every `MaterializedView` scan (see the module doc comment).
138pub struct OwnershipRewrite {
139 read_scope: ReadScope,
140 public_view_sets: Vec<String>,
141 processes_source: Arc<dyn TableSource>,
142 streams_source: Arc<dyn TableSource>,
143}
144
145impl std::fmt::Debug for OwnershipRewrite {
146 /// `dyn TableSource` carries no `Debug` impl, so `processes_source`/`streams_source` are
147 /// named but not expanded.
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.debug_struct("OwnershipRewrite")
150 .field("read_scope", &self.read_scope)
151 .field("public_view_sets", &self.public_view_sets)
152 .field("processes_source", &"<dyn TableSource>")
153 .field("streams_source", &"<dyn TableSource>")
154 .finish()
155 }
156}
157
158impl OwnershipRewrite {
159 /// `processes_source`/`streams_source` must be built from `MaterializedView::new(...,
160 /// query_range: None)` over the raw partitions (equivalent to `__processes__partitions` /
161 /// `__streams__partitions`) -- see `query.rs::make_session_context`: the audience lookup must
162 /// be time-unbounded, and must not go through the `SqlBatchView`-merged `processes`/`streams`
163 /// named tables. Used only by the semi-join/`async_events`/`thread_spans` branches -- the
164 /// views carrying an `audience` column, DDL-defined ones included, need neither.
165 pub fn new(
166 read_scope: ReadScope,
167 public_view_sets: Vec<String>,
168 processes_source: Arc<dyn TableSource>,
169 streams_source: Arc<dyn TableSource>,
170 ) -> Self {
171 Self {
172 read_scope,
173 public_view_sets,
174 processes_source,
175 streams_source,
176 }
177 }
178
179 /// `Aggregate(GROUP BY process_id, MAX(audience) AS resolved_audience)` over the raw,
180 /// time-unbounded `processes` partitions -- built once per `analyze()` call and reused at
181 /// every scan site the traversal visits (see the module doc comment). Only reached by the
182 /// semi-join/`async_events`/`thread_spans` branches now that `processes` itself carries a
183 /// physical `audience` column and filters it directly (the column-filter branch); the
184 /// aggregate still exists for those three because they have no `audience` column of their
185 /// own, not to reconcile disagreeing rows -- a process's own `audience` column never
186 /// disagrees across rows, so `MAX` is just a way to pull the single value out of the group.
187 fn per_process_audience(&self) -> datafusion::error::Result<LogicalPlan> {
188 LogicalPlanBuilder::scan(
189 "__processes__partitions",
190 self.processes_source.clone(),
191 None,
192 )?
193 .aggregate(
194 vec![col("process_id")],
195 vec![max(col("audience")).alias("resolved_audience")],
196 )?
197 .build()
198 }
199
200 /// The membership test on `column`: `column IN (audiences)`, `column IS NOT NULL` for
201 /// `EveryAudience`, or `lit(false)` for an empty list -- the fail-closed reading of "caller
202 /// has no audiences" rather than emitting `IN ()` and leaving its behavior to DataFusion.
203 /// An empty list is reachable in production: `public` has no built-in read grant, so a
204 /// caller matching no grant at all resolves to the empty set. Only called after `analyze()` has short-circuited on `ReadScope::All`, so the `All` arm
205 /// degrades to `lit(false)` rather than panicking if that invariant is ever violated.
206 fn membership_predicate(&self, column: Expr) -> Expr {
207 match &self.read_scope {
208 ReadScope::All => lit(false),
209 ReadScope::EveryAudience => column.is_not_null(),
210 ReadScope::Audiences(audiences) if audiences.is_empty() => lit(false),
211 ReadScope::Audiences(audiences) => column.in_list(
212 audiences
213 .iter()
214 .map(|a| lit(ScalarValue::Utf8(Some(a.clone()))))
215 .collect(),
216 false,
217 ),
218 }
219 }
220
221 /// `resolved_audience` membership (see [`Self::membership_predicate`]). No `coalesce` here:
222 /// the column is non-null by construction, because the extraction sites already coalesced a
223 /// never-stamped process's missing property to the deployment default before it was
224 /// materialized.
225 fn resolved_predicate(&self) -> Expr {
226 self.membership_predicate(col("resolved_audience"))
227 }
228
229 /// The column-filter branch: `audience IN (caller audiences)`, `audience IS NOT NULL` under
230 /// `EveryAudience`; `false` for an empty set (fail-closed, as [`Self::resolved_predicate`]
231 /// already does). The column is declared `NOT NULL` on
232 /// `blocks`/`log_entries`/`measures`/`otel_histograms` and non-null by construction (though declared nullable)
233 /// on `processes`/`streams`/`log_stats`, so there is no unstamped case either way -- a
234 /// DDL-defined view's `audience` column is a documented author obligation to keep non-`NULL`
235 /// the same way (see `view_definition.rs`).
236 fn audience_column_predicate(&self, table_name: &TableReference, field: &Field) -> Expr {
237 let raw = Expr::Column(Column::new(Some(table_name.clone()), "audience"));
238 // This rule runs after DataFusion's own TypeCoercion pass, so any non-`Utf8` column
239 // (`Dictionary(Int32, Utf8)` on the built-in views; `Utf8View` or a dictionary on a DDL
240 // view) must be cast to compare against `Utf8` literals. The cast is not a pruning
241 // barrier: `PruningPredicate` rewrites `cast(col) op lit` by applying the same cast to the
242 // column's min/max statistics (`datafusion-pruning`'s `rewrite_expr_to_prunable`).
243 // `verify_support_type_for_prune` accepts the dictionary -> Utf8 cast by unwrapping the
244 // dictionary and the `Utf8View` -> Utf8 cast as a string-to-string cast, with `IN` lists
245 // up to 20 items expanded to such comparisons. The bare-column arm below only skips a
246 // no-op cast for a column that is already plain `Utf8`.
247 let lhs = if field.data_type() == &DataType::Utf8 {
248 raw
249 } else {
250 cast(raw, DataType::Utf8)
251 };
252 self.membership_predicate(lhs)
253 }
254
255 /// The semi-join branch's shared `IN`-subquery plan: `per_process_audience` filtered by
256 /// `resolved_predicate`, projected down to `process_id` alone -- the one column an
257 /// `InSubquery` may project.
258 fn in_subquery_plan(
259 per_process_audience: &LogicalPlan,
260 resolved_predicate: &Expr,
261 ) -> datafusion::error::Result<Arc<LogicalPlan>> {
262 Ok(Arc::new(
263 LogicalPlanBuilder::from(per_process_audience.clone())
264 .filter(resolved_predicate.clone())?
265 .project(vec![col("process_id")])?
266 .build()?,
267 ))
268 }
269
270 /// The `async_events` branch's literal-valued `EXISTS`: `per_process_audience` filtered down
271 /// to the single process named by `process_id_literal`, conjuncted with `resolved_predicate`.
272 /// No projection: unlike
273 /// `InSubquery`, `EXISTS` has no single-column-projection requirement, so the two-column
274 /// (`process_id`, `resolved_audience`) shape is fine.
275 fn exists_for_process(
276 per_process_audience: &LogicalPlan,
277 resolved_predicate: &Expr,
278 process_id_literal: &str,
279 ) -> datafusion::error::Result<Expr> {
280 let subquery = LogicalPlanBuilder::from(per_process_audience.clone())
281 .filter(
282 col("process_id")
283 .eq(lit(process_id_literal))
284 .and(resolved_predicate.clone()),
285 )?
286 .build()?;
287 Ok(exists(Arc::new(subquery)))
288 }
289
290 /// The `thread_spans` branch's two-hop literal `EXISTS`: resolve `stream_id_literal` (the
291 /// `thread_spans` `view_instance_id`) through `streams` into the process it belongs to, then
292 /// apply the same `per_process_audience`/`resolved_predicate` check the column-filter branch
293 /// uses directly.
294 fn exists_for_stream(
295 &self,
296 per_process_audience: &LogicalPlan,
297 resolved_predicate: &Expr,
298 stream_id_literal: &str,
299 ) -> datafusion::error::Result<Expr> {
300 let subquery =
301 LogicalPlanBuilder::scan("__streams__partitions", self.streams_source.clone(), None)?
302 .filter(col("stream_id").eq(lit(stream_id_literal)))?
303 .join(
304 LogicalPlanBuilder::from(per_process_audience.clone())
305 .filter(resolved_predicate.clone())?
306 .build()?,
307 JoinType::Inner,
308 (vec!["process_id"], vec!["process_id"]),
309 None,
310 )?
311 .build()?;
312 Ok(exists(Arc::new(subquery)))
313 }
314
315 /// Parses `view.get_view_instance_id()` as a `Uuid` and returns its canonical
316 /// lowercase-hyphenated string form -- the form actually stored in `process_id`/`stream_id`
317 /// columns. `Uuid::parse_str` accepts several equivalent textual spellings (uppercase,
318 /// hyphen-less, braced) of the same UUID, but
319 /// only this canonical form round-trips through the data; using the raw, caller-supplied
320 /// spelling directly in a literal comparison would silently fail to match for any other
321 /// spelling of a legitimately materialized instance id. Defensive `Err` on parse failure --
322 /// the view constructors (`AsyncEventsView::new`/`ThreadSpansView::new`) already validate this
323 /// as a UUID at construction time, so this should not happen in practice.
324 fn canonical_view_instance_id(
325 view_set_name: &Arc<String>,
326 view: &Arc<dyn super::view::View>,
327 ) -> datafusion::error::Result<String> {
328 let raw = view.get_view_instance_id();
329 Uuid::parse_str(raw.as_str())
330 .map(|uuid| uuid.hyphenated().to_string())
331 .map_err(|e| {
332 DataFusionError::Plan(format!(
333 "OwnershipRewrite: view set '{view_set_name}' view_instance_id '{raw}' is \
334 not a valid UUID: {e}"
335 ))
336 })
337 }
338
339 /// Builds the predicate to wrap `mat_view`'s scan in. `Ok(None)` means "no predicate at all",
340 /// for either of two reasons: the public-view-set skip, or a guarded `view_instance(...)`
341 /// scan that `MaterializedView::instance_is_audience_guarded()` reports is already fully
342 /// authorized by `AudienceGuard::authorize_view_instance` (the call-level guard); `Err` is the fallback
343 /// for a view set matching none of the branches -- see the module doc comment's branch table.
344 fn predicate_for(
345 &self,
346 table_name: &TableReference,
347 mat_view: &MaterializedView,
348 per_process_audience: &LogicalPlan,
349 resolved_predicate: &Expr,
350 in_subquery_plan: &Arc<LogicalPlan>,
351 ) -> datafusion::error::Result<Option<Expr>> {
352 let view = mat_view.get_view();
353 let view_set_name = view.get_view_set_name();
354 if self
355 .public_view_sets
356 .iter()
357 .any(|s| s.as_str() == view_set_name.as_str())
358 {
359 return Ok(None);
360 }
361 // A guarded, non-`'global'` `view_instance(...)` scan is already fully authorized by
362 // `AudienceGuard::authorize_view_instance` before any row is read (see
363 // `MaterializedView::instance_is_audience_guarded`'s doc comment), so the semi-join/
364 // `async_events`/`thread_spans` subquery predicates below are redundant for it. This
365 // assumes a guarded instance's rows can never legitimately span more than one process --
366 // true for today's five view sets, but a future guarded view set whose instance can
367 // legitimately span more than one process would need to revisit this before its arm gets
368 // the same skip.
369 let skip = mat_view.instance_is_audience_guarded();
370 // The column-filter branch: views carrying a physical `audience` column -- processes,
371 // streams, blocks, log_entries, measures, otel_histograms, log_stats (global and per-process instances
372 // alike), and any DDL-defined view carrying the column. Filtered directly, no semi-join,
373 // no property_get. Checked ahead of the semi-join branch so a view set that has *both* an
374 // `audience` and a `process_id` column (every one of these does) takes this cheaper
375 // branch; keyed on schema introspection, so a view set that gains the column later
376 // upgrades automatically with no edit here.
377 if let Ok(field) = view.get_file_schema().field_with_name("audience") {
378 return Ok(Some(self.audience_column_predicate(table_name, field)));
379 }
380 // Qualified with the outer scan's own table name: once `DecorrelatePredicateSubquery`
381 // joins this scan with `in_subquery_plan`'s subquery, the combined schema holds a
382 // `process_id` column from both sides, so a bare, unqualified `col("process_id")` is
383 // ambiguous and `into_optimized_plan()` fails.
384 let outer_process_id = Expr::Column(Column::new(Some(table_name.clone()), "process_id"));
385 if view.get_file_schema().field_with_name("process_id").is_ok() {
386 // The semi-join branch: process_id-**column** views with no `audience` column of
387 // their own -- net_spans, otel_spans, images.
388 if skip {
389 return Ok(None);
390 }
391 return Ok(Some(in_subquery(
392 cast(outer_process_id, DataType::Utf8),
393 in_subquery_plan.clone(),
394 )));
395 }
396 if view_set_name.as_str() == "async_events" {
397 // The async_events branch: process-scoped, no process_id column -- the
398 // view_instance_id *is* the process_id string (`AsyncEventsView::new` parses it as
399 // a `Uuid`). Canonicalized
400 // before building the literal -- see `canonical_view_instance_id`'s doc comment for why.
401 if skip {
402 return Ok(None);
403 }
404 let process_id_literal = Self::canonical_view_instance_id(&view_set_name, &view)?;
405 return Ok(Some(Self::exists_for_process(
406 per_process_audience,
407 resolved_predicate,
408 process_id_literal.as_str(),
409 )?));
410 }
411 if view_set_name.as_str() == "thread_spans" {
412 // The thread_spans branch: stream-scoped, no process_id or stream_id column --
413 // resolve through `streams`. Same canonicalization as the async_events branch, keyed
414 // on `stream_id` instead of `process_id`.
415 if skip {
416 return Ok(None);
417 }
418 let stream_id_literal = Self::canonical_view_instance_id(&view_set_name, &view)?;
419 return Ok(Some(self.exists_for_stream(
420 per_process_audience,
421 resolved_predicate,
422 stream_id_literal.as_str(),
423 )?));
424 }
425 Err(DataFusionError::Plan(format!(
426 "OwnershipRewrite: no audience rule defined for view set '{view_set_name}'"
427 )))
428 }
429
430 fn rewrite_plan(
431 &self,
432 plan: LogicalPlan,
433 per_process_audience: &LogicalPlan,
434 resolved_predicate: &Expr,
435 in_subquery_plan: &Arc<LogicalPlan>,
436 ) -> datafusion::error::Result<Transformed<LogicalPlan>> {
437 let LogicalPlan::TableScan(ts) = &plan else {
438 return Ok(Transformed::no(plan));
439 };
440 let Some(table_source) = ts.source.downcast_ref::<DefaultTableSource>() else {
441 return Ok(Transformed::no(plan));
442 };
443 let Some(mat_view) = table_source
444 .table_provider
445 .downcast_ref::<MaterializedView>()
446 else {
447 // Not a MaterializedView (e.g. a table function's output) -- nothing to filter.
448 return Ok(Transformed::no(plan));
449 };
450 let Some(predicate) = self.predicate_for(
451 &ts.table_name,
452 mat_view,
453 per_process_audience,
454 resolved_predicate,
455 in_subquery_plan,
456 )?
457 else {
458 // No predicate: a public view set, or a guarded `view_instance(...)` scan
459 // the call-level guard already authorized.
460 return Ok(Transformed::no(plan));
461 };
462 let filter = Filter::try_new(predicate, Arc::new(plan.clone()))?;
463 Ok(Transformed::yes(LogicalPlan::Filter(filter)))
464 }
465}
466
467impl AnalyzerRule for OwnershipRewrite {
468 fn name(&self) -> &str {
469 "ownership_rewrite"
470 }
471
472 fn analyze(
473 &self,
474 plan: LogicalPlan,
475 _options: &ConfigOptions,
476 ) -> datafusion::error::Result<LogicalPlan> {
477 if self.read_scope == ReadScope::All {
478 // The internal/maintenance marker -- never a ReadPolicy's output. A true no-op, not
479 // "filter to a set containing everything" (see the module doc comment).
480 return Ok(plan);
481 }
482 let per_process_audience = self.per_process_audience()?;
483 let resolved_predicate = self.resolved_predicate();
484 let in_subquery_plan = Self::in_subquery_plan(&per_process_audience, &resolved_predicate)?;
485 plan.transform_up_with_subqueries(|node| {
486 self.rewrite_plan(
487 node,
488 &per_process_audience,
489 &resolved_predicate,
490 &in_subquery_plan,
491 )
492 })
493 .map(|res| res.data)
494 }
495}