Liking cljdoc? Tell your friends :D

Query materialization audit

Odoo 19 starts by asking whether named functions exist, then inspects relations, columns, constraints and indexes while installing modules. On pg-datahike v0.1.459 a lookup for one absent function could build the rows for every overload in PostgreSQL's procedure catalog, once during translation and again during execution. This audit follows ownership of intermediate rows from SQL analysis to wire delivery. The particular optimization a query can use depends on who owns the rows, how long they are visible and which rows the consumer needs.

Execution inventory

Producer and entry pointWhat gets builtLifetime and opportunity
Catalogs, sql/enrich-db-with-catalogs and catalog-read/compile-inputReferenced catalog declarations and entity maps in a speculative database. The SQL scanner finds relations in nested scopes as well as the top-level query.Declarations can be shared. Stored routines, schema objects and indexes come from the executing snapshot. Built-in routine descriptors have a process-wide name index. Supply matching rows to the ordinary evaluator when a mandatory predicate bounds the scan. For full catalog scans, reuse the translation overlay for the same simple statement and identical DB where its providers permit it.
Catalog joins, catalog-read/scoped-query-dbRow sets for joined relation OIDs, attribute numbers and constraints.Carry live and dropped column identity, namespace and physical/logical table names through joins. The existing scoped join producers restrict the input by relations proven by the plan. Filtering one alias in a self-join must preserve other aliases' rows.
Derived tables, VALUES, set operations and table functions, stmt/materialize-derived-select!, materialize-set-op!, materialize-table-functionTyped virtual attributes, row markers and intermediate records. Analysis also has a declarations-only path via materialize-output-schema!.Separate column naming, OIDs and typmods from row production. Row-producing work belongs to the bound statement snapshot. Use existing restriction pushdown for inert projections. Preserve duplicate multiplicities, NULL padding, set-operation order and the number of volatile calls.
Ordinary and recursive CTEs, sql/materialize-withs!, stmt/materialize-recursive-rows!, recursive-demand-rowsA query-local relation, a Datalog rule or iterative working rows. Some parameterized producers defer rows until Execute.Multiple consumers can require one evaluation with independent reads. A single consumer with a lawful stopping condition can consume rows on demand. The existing bounded recursive path demonstrates this for admitted shapes. Sorting, shared consumers, cycles and side effects change the proof.
Correlated subqueries and LATERAL, expr/eval-correlated-scalar, stmt/run-correlated-specRows parameterized by the current outer tuple. Uncorrelated membership subqueries can produce a statement-local set.A key set can replace repeated evaluation for proven inert membership tests. Outer bindings, SQL three-valued logic, scalar cardinality errors and volatile expressions determine whether reuse is valid.
Transaction command views and write sources, read-view/materialize, locked-write-targets, materialize-insert-candidateA private write projection over committed rows, matched target/source tuples and evaluated insert candidates.Command snapshots, row-lock rechecks, savepoints and transaction-local effects determine ownership. The point-read path already avoids a full view for eligible reads. Re-evaluate a changed target at the proper snapshot. Preserve sequence, default, trigger and RETURNING evaluation counts.
Portals and cursors, PgWireServer.handleExecuteMsg and server/cursor-fill!Extended-query Execute can retain an eager result across suspension. SQL cursors maintain position and a row cache.Measure first-row latency, retained bytes, and rows consumed. Incremental delivery must retain portal snapshot, ordering, backwards fetch semantics where offered, and close/error cleanup.
Persisted results, exec-ddl-refresh-matview, secondary-index builds, mirror snapshots and journal checkpointsDurable state with ownership, publication and restart obligations.Track separately from SQL query intermediates. Removing a query-local copy cannot replace durable publication or advance a replication acknowledgement.

Historical and filtered databases have a specific overlay contract. virtual-db/with-data exposes query-local datoms while retaining the source view's visibility for user data. A snapshot-only optimization must keep that property or use the full path. Session catalogs such as pg_cursors and pg_prepared_statements also depend on session state. Registered catalog providers can supply arbitrary rows. Cross-session row caching would change their contract.

Changes in this batch

  • A shared single-relation planner handles mandatory literal-name equality on information_schema.columns.table_name and pg_proc.proname. Both use the ordinary projection and residual predicates. Routine execution combines all built-in overloads of the name with the executing database's stored definitions. The prepared plan carries a name restriction and declarations. Each execution obtains its own candidates.
  • Ordinary index and routine catalog scans can reuse an already built overlay within the same simple query on its exact source DB. Prepared execution refreshes the rows. Provider overrides continue through the existing dynamic-provider path.
  • The regression checks cover all overloads, an absent function, prepared visibility across a savepoint rollback, same-statement enrichment count, and index creation between Parse and Execute. The index-definition comparison uses the SELECT from PostgreSQL 18.6 index_including.sql line 120 on a simple B-tree fixture. This covers the catalog query independently of the full upstream INCLUDE-index scenario.

Work measured on Odoo startup queries

A warm SQL-handler replay alternated the v0.1.459 full-input path with the scoped path in the same JVM. The fixture had 3,411 procedures and 21 indexes. Each timing is the range of two block medians, five executions per block. Instrumented executions counted rows separately from the timed executions. The host also ran the integration workload.

QueryFull catalog rows built per execution, before → afterMedian time, before → after
Odoo unaccent discovery6,822 → 01,233–1,758 ms → 32–37 ms
Odoo word_similarity discovery6,822 → 01,186–1,664 ms → 7–11 ms
Odoo index existence check42 → 2175–89 ms → 52–90 ms
Upstream index-definition query42 → 2132–54 ms → 21–37 ms

Both routine probes returned zero rows on PostgreSQL 18.6 and on the adapter. The index queries returned the same index and definition. During a fresh Odoo installation the two routine queries together took 4.6 ms on native PostgreSQL, 2.80 s on v0.1.459 and 1.42 s on the candidate. These cold query times include startup effects. The table measures the catalog phase only. The other producers above were audited in source.

Follow-on order

  1. Replay Odoo's constraint installation in a growing transaction. The released installation spent 127 seconds in 360 inserts into ir_model_constraint and 72 seconds in 361 discovery reads by the end of that phase. Each insert has two scalar subqueries over user tables. The read joins two user tables on module identity. Measure command-view reconstruction, subquery evaluations and candidate rows independently. Pair the application SQL with the related PostgreSQL subselect and join cases before changing either path.
  2. Measure XML-ID upserts and index discovery by cumulative time, row count and full materializations per execution. Use PostgreSQL's insert_conflict and index-definition queries alongside the application probes. For named indexes, account for both stored index objects and synthetic indexes before narrowing the producer. Check duplicates and namespace collisions using the native query as oracle.
  3. For recursive view inheritance, measure working rows, distinct consumers and peak retained rows on Odoo's real query. Compare with PostgreSQL's recursive and CTE executor rules before extending demand-driven execution. The existing recursive LIMIT fast path provides a control.
  4. Instrument the first materialization and any repeat separately for Parse, Bind, Execute and portal resume. Report rows produced versus consumed and calls to volatile expressions. Compare native rows, SQLSTATE, OIDs and command effects alongside time. These measures distinguish duplicate work from expensive work required once.

PostgreSQL makes separate decisions about folding a CTE, producing its rows and retaining them for consumers. Its Material node can fill a tuplestore as its parent requests tuples, and CTE scans can share produced tuples through independent read pointers. These are useful reference points for the next operator changes. CTE planning · Material executor · CTE scan

Statement snapshots in INSERT VALUES

An Odoo constraint-definition insert contains two scalar subqueries. Replaying an insert of this form with changing source data exposed a correctness issue. On v0.1.459, identical SQL inserted the first lookup result three times after the source changed from 1 to 2 to 3. The VALUES translator had put a concrete value in a reusable INSERT plan. Scalar VALUES cells containing a subquery now use the existing execution-time projection mechanism. PostgreSQL 18.6 and the adapter agree on source updates in the same transaction, missing-row NULLs, parameter binding and arithmetic around a lookup. A scalar producing multiple rows raises 21000 at execution. Top-level set-returning VALUES cells have a separate row-expansion path that still warrants audit.

Where the Odoo profile points next

A 65-second Flight Recorder sample covered the candidate's late base XML and access CSV loading. Of 3,782 runnable-thread samples, the innermost pg-datahike frame was columns-by-relation in 738, schema-hints* in 602 and derive-virtual-tables* in 508. Together these account for 49% of that interval's samples. The registered-column index iterates over known relations and requests their columns. Schema hints and virtual-table derivation also enumerate metadata. This is the next performance priority. The sample describes one installation phase.

Measure how often each lookup visits unrelated relations and how many times the same metadata is rebuilt following ordinary DML. Compare a relation-scoped metadata reader with reuse keyed by proven catalog dependencies. Test rename, drop, rollback, concurrent DDL, native Datahike schema changes, temp relations and historical views. Use Odoo's constraint discovery and recursive view inheritance as consumers, paired with upstream schema and join regression cases. The first checkpoint is identical results and bounded metadata work as unrelated tables are added.

Can you improve this documentation?Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close