Installing, upgrading and uninstalling modules
Status: the addon platform is complete. The rules that schedule installs, upgrades,
and uninstalls, the one-transaction runner, hooks, init() and _register_hook(), the post-commit
phase, data and view loaders (erp-data), CLI operations (erp module), and authorized uninstalls
are in place (erp_modules::system::ModuleSystem). Administrator groups are planned (until then
only the superuser may run module operations).
Caller stack safety
Section titled “Caller stack safety”Lifecycle callers use the ordinary async methods directly. The module engine owns heap
indirection for its large inner lifecycle future, so initialization, immediate installation and
upgrade do not require caller-side Box::pin workarounds. SPEC-MOD-059 exercises those operations
on an explicit 2 MiB thread with stored model/data assertions. This bounded framework fixture
does not guarantee the stack requirements of arbitrary addon hooks or recursive callbacks.
Transaction and post-commit semantics remain those documented below; returned errors and
post-commit reports must still be checked. Future-layout diagnostics are covered by the module tests.
Authorized uninstall with confirmed impact
Section titled “Authorized uninstall with confirmed impact”The native ModuleSystem engine has a separate two-call uninstall seam under
ADR 0083. It requires a trusted InstallAuthorizer backed by current primary
session authority. A fingerprint acknowledges the described effect; it is never
an authorization credential or an idempotency key.
Call preview_uninstall_authorized(names, authorizer), present the complete
returned UninstallImpact, then pass its fingerprint().as_str() unchanged with
the same requested names to uninstall_authorized(names, fingerprint, authorizer).
The executor rechecks authority, rebuilds the shared plan under transaction locks
and compares the new fingerprint before effects. A changed plan returns Conflict:
Uninstall impact changed; preview again before confirming. Obtain another
preview and confirmation instead of automatically replaying the destructive call.
Preview rolls its transaction back and changes no catalog, data, schema, audit or
registry generation.
The supported subset admits the built-in ErpDataLoader or no loader in
bounded callback-free compositions. Survivor record deletions requiring any unlink
implementation remain refused, including the built-in base implementation.
The full base addon composition is currently
refused by the native-schema admission (currently ir_dated_parameter index
support), and its ir.actions.actions register hook is also outside the described
plan. This is not yet a
full-base/browser uninstall capability.
Within that subset it removes complete ordinary model tables and their
explicit reflection, XML-identity and queued post-commit metadata. Reverse
dependents are included. Counts, including aggregate target cardinality, are
decimal strings, and the public impact contains no raw record IDs or values.
The identity bound includes metadata rows and dropped schema objects:
10,000 total identities, 65,536 serialized impact bytes and at most 512 current-schema
tables. Planner SQL statements have a 5,000 ms deadline, lowered further when
the active operation already has a shorter limit. This planner cap does not
cover the pre-BEGIN opening probe or the earlier lifecycle/authority opening.
Preview takes ACCESS SHARE relation locks and describes a repeatable-read snapshot,
allowing ordinary reads and writes. Confirmation independently recomputes under broad
ACCESS EXCLUSIVE locks on current-schema ordinary tables and retains those locks through
commit. Changes after preview therefore require a fresh confirmation fingerprint.
An id-less metadata relation is checked for matching references without selecting a fictional
id. Matching references refuse as an unsupported survivor foreign-key effect; references
only to retained metadata do not imply a deletion or cascade.
Unsupported paths refuse before effects. Registered host lifecycle services also refuse: their
required asset or other publication work is neither executed outside the described plan nor silently
skipped. An empty configured package runtime remains an opaque callback provider. In particular,
this seam does not run custom data-loader purges, uninstall hooks, package callbacks, non-base register
hooks, selection policies, survivor-model extensions or deletions requiring unlink behavior, many2many removal
or copied-view cascades. It refuses unsafe database triggers/rules, view and FK
dependencies, partitioned/foreign tables, inherited-table removal, row-security
membership sources and generated company-restriction cleanup.
The one trigger exception is an exactly attested, registry-declared built-in
policy signal trigger: its structure, owner/signature, complete native function
body and pinned configuration must match. The ORM helper checks the exact native
body; catalog SQL checks the sole expected configuration entry using PostgreSQL’s
quote_ident schema representation. Reordered or extra search-path entries refuse.
A matching name alone is insufficient.
Its policy bump is included as an explicit bump_policy impact effect; the
registry bump is described as bump_registry. Arbitrary callbacks remain refused.
Catalog planning sources are independently limited to 10,000 rows and 1,048,576
serialized row bytes per source, before they are fetched. Relevant trigger
definitions also have count and function-body byte admission limits. Dropped-table
columns, defaults, constraints, indexes, triggers and owned sequences are counted
and bound by their catalog identities/definitions; public drop_schema_objects
metadata reports their count without exposing the definitions. Each dropped table’s
schema definitions must fit 1,048,576 bytes both per table and in aggregate,
and the shared target-identity cap. Private canonical serialization is bounded
to 8,388,608 bytes by a capped writer before extending its buffer; the public
impact still has its independent 65,536-byte admission limit.
Application schema/function DDL must honor the existing SCHEMA_LOCK protocol,
and the runtime role must have no DDL ownership or schema CREATE authority.
Privileged operator DDL outside that protocol is outside this admission guarantee.
Authorized preview and confirmation require a clean connection lookup state.
Before any lazy BEGIN or automatic Signal read, a metadata-only
probe runs on the same held, fully elevated System connection while its transaction
is still Idle. pg_catalog must be the first effective schema, including any
temporary namespace. An implicit temporary namespace ahead of it refuses even
when empty; the engine does not silently normalize the path. A configured Signal
store must be an ordinary persistent table that is not a partition, has no row-level
security and takes no part in inheritance; its key is native text and its weight
int8, with no generated columns, no enabled user triggers, no rewrite rules and no
non-catalog sum overload on the search path. Any other shape refuses while Idle,
before the automatic generation read; a store that passes admits that read, which is
never suppressed. The pre-BEGIN probe leaves a check-then-use window against concurrent
privileged DDL (ADR 0186, decision 3). The unconfigured minimal native composition retains
direct durable generation reads/bumps under the operation locks. The probe obtains no
second pool connection and issues no explicit table locks; its catalog SELECT naturally takes
implicit catalog read locks. This conservative precondition grants no authority
and is rechecked inside the lifecycle transaction after each authorizer.
Before planner data scans, the engine requires this catalog precedence and native
scalar/array column types across current-schema ordinary tables. Custom/domain
column types, custom table/index access-method or operator-class provenance,
generated columns refuse. Expression/partial indexes refuse on actual planner
scan tables: core metadata sources, dropped targets, dynamic FK sources and both
counterpart tables of incoming/outgoing FKs incident to writes. Cross-schema FK
counterparts refuse. Unrelated native login-throttle partial age indexes are
allowed when their tables do not enter that scan inventory. Present CHECKs
and INSERT defaults on the core writable tables must match the exact native
allowlist, after native dependency checks performed before expression deparsing.
All ordinary-table CHECK/default/trigger-condition dependency admission also
runs before dropped-schema deparsing, with separate count/byte bounds. Native
column types include inet. Application overloads of used planner operators and
routines named like native built-ins refuse even with pg_catalog first; unrelated
unused extension operators are outside that symbol fence.
The native audit sequence/time and signal defaults remain supported; an addon
callback hidden in a CHECK/default is refused rather than executed.
Metadata FKs with live SET NULL/SET DEFAULT references refuse. A CASCADE
reference is admitted only when every source row is explicitly planned and its
table is deleted before the referenced target table; unordered cascades refuse.
base, web and their required dependencies are protected, including indirect
removal. Pending lifecycle work must be resolved first; a refused confirmation preserves
that pending state. Shadowed SQL sources and a changed schema after trusted
authorization refuse admission. Unsupported effect categories return an explicit
error before any uninstall effect; callers must not treat a refusal as an empty plan.
Durable registry signal and lifecycle audit storage must already exist. The engine binds confirmation to the database, actor/session, durable generation, available addon content and exact target identities, so replacing rows while retaining their count still requires a fresh preview. Installed artifact attestation remains a separate prerequisite (planned); available catalog/source content alone does not establish it. This package enables no browser uninstall route.
Successful removal and its insert-only lifecycle audit commit atomically. Use
OperationOutcome::orm afterward and inspect OperationOutcome::post_commit:
a post-commit failure is reported after the uninstall has committed and cannot
be treated as a rollback. The existing install audit history is preserved.
Remote validation and browser delivery status are recorded in the engine design;
this guide is not a claim that broader browser/multi-node acceptance has passed.
The proposed native SQL-object contract does not add callable lifecycle APIs yet. In particular, SQL-object guards are not an exemption from the current confirmed-uninstall restrictions on hooks. Do not declare SQL bodies, grant policies or SQLSTATE registrations in a manifest or model file.
Making a native addon installable on a served node
Section titled “Making a native addon installable on a served node”A served node (erp server) and the lifecycle commands (erp module install | upgrade | uninstall) offer two
kinds of addon from their addon directory: data-only addons (manifest, model files, data; see
the data-only guide) and the native addons compiled into the erp binary. A folder of the
addon directory that holds a Rust crate (Cargo.toml, src/) but is not compiled in is not offered: the Addons
page does not list it, and every install route refuses it by name, the browser, erp module install and an
install that would pull it in as a dependency alike. The refusal ends with
this binary does not link the addon's native code: <reason>.
The native addons the binary compiles in are one list, crates/erp-cli/src/native_addons/names.rs:
LINKED: the addons linked intoerp, in dependency order.crates/erp-cli/src/native_addons.rsholds their descriptors (DESCRIPTORS, same order), which every composition site passes toModuleSystem::builder(..).code(..);crates/erp-cli/build.rsreads the same names for the per-addon identity receipts, so the linked code and the receipts cannot drift apart.NOT_LINKED: the addon crates ofaddons/that are left out on purpose, each with its reason. Today these are the declared bridge addons that have a manifest and a dependency declaration but no model and no data yet (delivery,product_expiry,purchase_stock,sale_stock,stock_account,stock_delivery,stock_dropshipping,stock_landed_costs,stock_sms): offering one would install an application that promises features it does not have.
To make a new native addon installable on a served node:
- Add its crate to
[dependencies]ofcrates/erp-cli/Cargo.toml(not[dev-dependencies]: a test binary links dev-dependencies, the served binary does not). - Add its name to
LINKEDand itsADDONdescriptor toDESCRIPTORS, at the same position. - If it is not ready to be offered, add it to
NOT_LINKEDwith the reason instead.
The test every_addon_crate_is_linked_or_excluded_with_a_reason (crates/erp-cli/tests/served_account_stock.rs)
fails when a crate under addons/ is in neither list, in both, or when the descriptors and names differ, so a new
addon cannot be left out silently. The addon catalogue writes one server log line per addon it does not offer,
addon catalogue: <name> is not offered for installation: <reason>; for the declared bridges the reason starts with
declared, no behaviour yet and then says what the addon holds (only its manifest and dependency declaration, or
storage models without access rows, data or operations), for a folder with a crate the binary does not link it says
the folder holds a Rust crate (Cargo.toml or src/) of a native addon that this binary does not link. A folder named in NOT_LINKED that holds no crate gets its own refusal, never the NOT_LINKED reason.
What your manifest controls
Section titled “What your manifest controls”| Key | Effect on the lifecycle |
|---|---|
depends | Installing your addon installs these first; uninstalling one of them uninstalls your addon. Your addon always loads after them, and only the order of dependencies is guaranteed: an addon that overrides another must depend on it. |
auto_install | true: installed as soon as all depends are installed or being installed, and at least one of them is being installed now. A list (['sale', 'stock']) restricts the triggers: the other dependencies are installed with it, not required. This is how glue addons work. |
icon | The addon’s icon where the web client lists addons: the Settings sidebar (for an addon whose settings have no root menu of their own) and its tile on the Apps page. "lucide:<name>", the same form as a menu’s web_icon (for example icon = "lucide:palette"); any other value refuses the manifest when it is read. A name the client does not ship shows the default icon with a console warning. Without it the addon shows its first letter. An addon that appears in any menu or sidebar should declare one. |
countries | Two-letter ISO 3166-1 country codes ("BE"; any case, stored upper case); anything else ("BEL", "B1", a path) is refused when the manifest is read. With auto_install: only when a company is in one of these countries. Company countries arrive with res.company in M3; until then an operation that would auto-install such an addon fails with “Module “x” auto-installs only for companies in BE, but the companies’ countries are not known until res.company arrives (M3); install “x” by name in the same operation to include it” instead of skipping it silently. Naming the module works with every entry point (button_immediate_install takes no options); code driving a Catalog directly can also pass InstallOptions::with_company_countries (a list of CountryCode). |
excludes | Installing your addon while one of these is installed (or the reverse) is refused: Modules "A" and "B" are incompatible. |
category | "Sales & CRM/Tools" creates the categories Sales & CRM and its child Tools (external IDs base.module_category_sales_and_crm and …_tools). In a category flagged exclusive, the installed modules must all be dependencies of one of them. Empty segments ("A//B") and segments with leading or trailing whitespace ("Sales / Tools") are refused when the manifest is read. Two categories whose external IDs would be the same ("A/B" and "A B" both give module_category_a_b, as in Odoo, where they silently merge into one category with the wrong parent) are refused by update_list with a message naming both: rename one of them. |
installable | false: the module is listed as uninstallable. Asking to install it, or a module that depends on it, is an error (Odoo silently drops it later). |
version | Stored as the installed version after install and upgrade; 20.0.1.2 becomes 1.2.0 (ADR 0009 §5). |
data, demo | Loaded in this order on install (init mode) and upgrade (update mode). Demo files load only when every dependency has demo data (base takes the database’s demo flag). |
pre_init_hook, post_init_hook, uninstall_hook | Functions of your addon, see below. |
One transaction per operation
Section titled “One transaction per operation”The transaction guarantee below covers failure before the lifecycle commit. Restoring an older executable after a successful upgrade does not undo its committed schema or data migration. Manifest versions select migration steps; they do not certify that an older binary can serve the upgraded database. The separate schema compatibility admission proposal is planned; it adds no manifest key or active runtime check yet.
An install, upgrade or uninstall is one PostgreSQL transaction (ADR 0009 §2): when anything fails (a hook, a data file, a schema change), nothing of the operation is kept, not even the modules that were processed before the failure. Odoo commits each module on its own; ERPForAll does not.
The error names the module and the step that failed (Error::StepFailed); the step’s own error is
its source, so print the whole chain (std::error::Error::source, or anyhow’s {:#}) to see both:
Module "library": post_init_hook 'fill_shelves' failed caused by: <your hook's error>Module "library": data file 'data/books.xml' failed caused by: <the loader's or parser's error>Module "library": init() of library.book failed caused by: <your init's error>Module "library": _register_hook() of library.book failed caused by: <the override's error>_register_hook() failures name the module that declares the model, whichever override failed. When
the data loader’s purge fails on uninstall, the error names every module being removed (“Modules a, b:
the data loader’s purge before uninstall failed”): the loader purges them together.
After a successful operation, use the returned ORM (outcome.orm) and drop the one you called with:
the old ORM still has the registry from before (no models of the installed modules, the models of
uninstalled ones still there). The outcome is #[must_use]; ...await? alone does not look at
outcome.post_commit, which is where post-commit failures are reported.
Each operation runs with a lock_timeout (default 30 s) and a statement_timeout (default 30 min),
set right after the operation lock; the host can lower them (ModuleSystemBuilder::lock_timeout,
::statement_timeout), never raise them: until a planned change moves the schema sync’s own index builds and
backfills out of the operation transaction, these limits are what bounds the locks it holds (ADR 0022
§10): until then module operations run the ORM’s schema step inline (Transaction::init_models, whatever
the size of the tables) and not the large-table form init_models_with; a session that already has lower limits keeps them. The ORM’s own schema bounds (10 s / 5 min)
never raise them either, and apply to each schema statement of an install or upgrade. A statement that cannot get a lock fails the operation with “A statement of a
module operation could not get a database lock (SQLSTATE 55P03; lock_timeout is … ms)”
(Error::LockNotAvailable); one that is canceled with ”… was canceled (SQLSTATE 57014;
statement_timeout is … ms)” (Error::StatementCanceled). The same codes come from a NOWAIT lock or
from an administrator’s pg_cancel_backend, so the message names the limit without claiming it was
the cause; PostgreSQL’s own message, the source, says which. The errors carry the limit that was in
force for the failed statement as a Duration (zero for no statement_timeout). Index builds and
backfills on large tables belong in the post-commit phase (below); creating them inside a hook runs
into these limits on big tables.
Hooks, data loaders and init() / _register_hook() methods run in the operation’s transaction but
cannot end it: tx.commit(), tx.rollback(), tx.commit_pipelined() and tx.switch_orm() return a
Programming error (“this transaction belongs to a module operation, which commits or rolls it back
itself”). A raw COMMIT or BEGIN sent as a statement cannot be refused; the operation notices right
after the hook, stops with Error::OperationTransactionEnded and resets the transient module states.
What the hook had already committed stays in the database, so the error says it may hold a partial
change.
Inside the transaction, each module you install gets its own registry step, so your code sees what it would see in Odoo:
pre_init_hookruns on the registry without your addon: your models and tables do not exist yet. Use raw SQL (tx.execute,tx.query), for example to pre-create a column so that a new computed column does not have to be filled row by row.- Your models are added; their tables are created or altered, then
init()runs on every model your addon declares or extends (also for models of other addons that you extend). datafiles in manifest order, thendemofiles.post_init_hookruns: your models, tables and data exist.- The module is marked
installedwith its version.
Upgrades run steps 2, 3 and 5 for each upgraded module (data in update mode). After the last module,
_register_hook() runs once on every model of the final registry, never on the intermediate ones. So a
hook may check rows that a data file of the same operation creates, such as a group your release adds:
erp module install | upgrade | uninstall loads the installed set first without the hooks, and the
operation runs them at its end. A server start runs them on its load: started on a database its release
was not upgraded on, the server stops at the hook that finds the rows missing, instead of serving. When
an installed module gains a new dependency in an upgrade, the dependency is installed first in the same
transaction.
Uninstalling runs every uninstall_hook in reverse load order (dependents first) while the modules’
models and data are still there, then the data loader’s purge (it deletes the records the
modules’ external IDs name in models that stay installed), then drops the columns the modules’ fields
added to other models, the tables of models that disappear and their many2many relation tables, and
removes the modules’ external IDs and post-commit steps. Nothing is dropped with CASCADE: if a view,
foreign key or index of another module (or of the administrator) uses a table or column being removed,
the uninstall fails and names it (“Cannot remove the schema of modules x: cannot drop table x_thing
because other objects depend on it (view y_report depends on table x_thing); remove the objects that
use it first”). PostgreSQL’s DROP COLUMN would silently remove an index or constraint of the same
table that uses the column together with other columns; those are refused too (”… cannot drop columns
that other objects use together with columns that stay (index y_mixed_idx on x_thing (name,
x_note)) …”), unless the removed modules declared them. An index or constraint on removed columns only
goes with them. A table to drop that no longer exists (removed by hand) fails the uninstall with its
name (“Cannot remove the schema of modules x: table x_thing_y_tag_rel does not exist (it was removed
outside ERPForAll)”). A table that a model or relation that stays still maps to is never dropped: if a
removed model and a kept one (or one of the module system’s own models) share a _table, the uninstall
fails naming the table and both models (”… table x_shared is used by model a.old, which is removed, and
also by model b.keep, which stays”). The column of a custom field (x_…, ADR 0036) that the uninstall breaks (for
example a stored related field through a removed field) stays: custom fields are the database
owner’s, and a dropped custom field keeps its column. Refused as well:
- a module that still owns records (external IDs) in a model that stays installed, for example a
partner your data file created. Without a data loader the uninstall is refused with an error saying that the module owns records of models that stay installed (for example res.partner: 3) and that no data loader is installed to remove them — delete those records in your
uninstall_hook(and their external IDs) to uninstall now. With a loader whose purge left some: ”… after the data loader’s purge it still owns records …”; - a module whose source is gone, or whose manifest says
installable = false: ERPForAll finds the tables to drop from the module’s declarations, so restore the source first (Odoo uses itsir.modelmetadata instead).
Only one operation runs at a time per database: a second one, and any scheduling call
(button_install, button_upgrade, button_uninstall, button_reset_state, update_list), is
refused at once with “ERPForAll is currently processing another module operation.” A plain load
(ModuleSystem::load, server start) that finds scheduled modules runs them first; it waits for an
operation in progress (up to 30 min, ModuleSystemBuilder::operation_wait_timeout) instead of failing.
Only the superuser (uid 1, the System principal with full elevation) may run module operations until
M3 adds administrator groups; sudo() of another user is not enough, and the environment must come from
the ORM of the same module system (ModuleSystem::load()/initialize outcomes): an environment made by
another ORM, even on the same database, is refused with “Access denied to module.<method>: the
environment does not belong to this module system’s ORM”. An installed module whose dependency is not installed (a database edited by
hand, a restored dump) stops the load and every operation with “Inconsistent module states in the
database” listing the pairs, instead of loading without the module. If a failure leaves
modules scheduled (to install, to upgrade, to remove), they are reset to uninstalled /
installed; when another operation started in between, the reset is skipped and both errors are
returned (button_reset_state resets later). A scheduled module whose source disappeared, or that the
dependency graph leaves out, fails the next operation with the list of such modules and why.
Data files
Section titled “Data files”Data and demo files are read from the addon folder: regular files only (a symbolic link, a path
under one, or a file with several hard links is refused), at most 64 MiB each (the host can lower the
limit with ModuleSystemBuilder::max_data_file_bytes). A module may list at most 512 data and demo files
and one operation reads at most 1 GiB of them in total; the host can lower both
(max_data_files, max_operation_data_bytes), and a module over them fails its operation naming the
limit. manifest.toml is read the same way (a regular file with one link, at most 256 KiB), on the
blocking pool. XML files are handed to the data loader one operation at a
time; CSV files are read whole first (a known limit until the CSV reader streams). The loader must
consume every operation of a file: if it returns early, or drops a parse error, the operation fails
anyway.
Name the hook in manifest.toml and give one implementation per name:
name = "Library"depends = ["base"]post_init_hook = "fill_shelves"use erp_modules::hooks::{HookImpl, HookKind};use erp_orm::{BoxFuture, Transaction};
fn fill_shelves(tx: &mut Transaction) -> BoxFuture<'_, erp_fields::Result<()>> { Box::pin(async move { tx.execute("UPDATE library_book SET shelf = 'A' WHERE shelf IS NULL", &[]).await?; Ok(()) })}
#[erp_modules::hooks::linkme::distributed_slice(erp_modules::hooks::HOOKS)]#[linkme(crate = erp_modules::hooks::linkme)]static FILL_SHELVES: HookImpl = HookImpl::new("library", HookKind::PostInit, "fill_shelves", fill_shelves).at(file!(), line!());(Write it exactly like this: HookImpl::new(addon, kind, name, function) and .at(file!(), line!()),
which error messages point at; a #[hook] attribute in erp-sdk will generate it later. The same form
is compiled in crates/erp-modules/tests/system_specs.rs, linked_hooks_run.)
The pairing is checked when the module system starts: a hook named in a manifest without an
implementation, two implementations of one hook, or an implementation the manifest does not name is an
error naming the addon, the hook kind and the source location. Hooks run as the superuser, inside the
operation’s transaction; returning an error aborts the operation. Odoo’s post_load does not exist
(no runtime patching, ADR 0009 §6).
Migrations
Section titled “Migrations”An upgrade runs the addon’s migrations for the versions between the installed one and the manifest’s:
#[erp_sdk::migration(addon, version, stage)] functions and migrations/<version>/<stage>-*.sql
files, in the stages pre, post and end, inside the operation’s transaction. See
migrations.md.
init() and _register_hook()
Section titled “init() and _register_hook()”Every model has both as no-op methods of base; override them like any method and call super:
#[methods(Book, addon = "library")]impl Book { #[method(override)] async fn init(this: &RecordSet<Book>, tx: &mut Transaction, sup: Super) -> Result<()> { tx.batch( "CREATE OR REPLACE VIEW library_book_titles AS \ SELECT id, upper(name) AS name FROM library_book", ) .await?; sup.call(tx, this.as_records(), ()).await }
#[method(override)] async fn _register_hook(this: &RecordSet<Book>, tx: &mut Transaction, sup: Super) -> Result<()> { // registry-wide setup; runs once per registry build, after all modules are loaded sup.call(tx, this.as_records(), ()).await }}init() creates SQL views, indexes or functions after the table exists; it runs on install and
upgrade of any addon that touches the model. (Tested in crates/erp-test-models/tests/model_hooks.rs.)
Slow schema work: the post-commit phase
Section titled “Slow schema work: the post-commit phase”Work that cannot run in a transaction (CREATE INDEX CONCURRENTLY) or would hold locks too long is
scheduled from a hook and runs after the operation commits, each step on its own. A step is a
structured action, not SQL text: the queue (ir_module_post_commit) is read back and run with the
module system’s database rights, so there is nothing to inject into. Two actions exist:
PostCommitAction::create_index and PostCommitAction::analyze.
use erp_modules::{ CreateIndex, IndexColumn, IndexMethod, IndexName, ModuleName, PostCommitAction, PostCommitKey, TableName, schedule_post_commit,};
let library = ModuleName::new("library") .map_err(|e| erp_fields::Error::programming(e.to_string()))?;let table = TableName::parse("library_book")?;let index = CreateIndex::new( table.clone(), IndexName::parse("library_book_name_trgm")?, vec![IndexColumn::new("name")?.with_opclass("gin_trgm_ops")?],)?.method(IndexMethod::Gin);let trgm = PostCommitKey::parse("book_name_trgm")?;let analyze = PostCommitKey::parse("analyze_books")?;schedule_post_commit(tx, &library, &trgm, &PostCommitAction::create_index(index)).await?;schedule_post_commit(tx, &library, &analyze, &PostCommitAction::analyze(table)).await?;schedule_post_commit only works from the transaction of a module operation (a hook or data loader the
module system runs) acting as the System principal: any other transaction is refused (Programming
for an unmanaged one, Access for another principal).
Rules:
- Table, column, operator class and index names are 1 to 63 bytes of
a-z,0-9,_, not starting with a digit (table and index names also not withpg_, PostgreSQL’s catalogs); they are validated when the value is made, stored in columns (kind,table_name,index_name,specas strict JSON of at most 4 KiB) and quoted when the statement is built. An index has 1 to 32 columns, an optional operator class per column, an access method (btree,hash,gin,gist,brin) and may beunique(). A step must be idempotent and may run more than once: a failed step runs again in every later phase until it succeeds or has failed three times (MAX_POST_COMMIT_ATTEMPTS), when it is parked (see below), and a phase that was interrupted may have run a statement whose result was never recorded. Both actions are (CREATE INDEX ... IF NOT EXISTS,ANALYZE). The key is 1 to 64 bytes ofa-z,0-9,_,.,-, unique per module; scheduling the same key again replaces the step (and makes it run again, also when a phase is running the old one: that run is not recorded and shows inoutcome.post_commit.superseded). The runner reads each row again before running it: a row changed in the table directly that no longer parses (a table name that is SQL, an unknown kind, a spec with an unknown key) is never run; it is markedfailedwith the reason and reported inoutcome.post_commit.invalid. - The queue is closed to everything but the module system. Only the module system writes
ir.module.post_commit: creating, changing or deleting its rows through the ORM is refused, for the superuser too. Database initialization revokes every privilege on the table fromPUBLIC, and the server setup callserp_modules::revoke_post_commit_access(tx, role)for the role that serves requests, next toTransaction::grant_signal_request_role. - A failed
CREATE INDEX CONCURRENTLYleaves an invalid index thatIF NOT EXISTSwould accept; an index step drops an invalid index of that name before the retry, but only when it is on the step’s table (an index of that name on another table fails the step and is left alone), and after the statement checks that the index exists, is valid and is on the table (otherwise the step isfailed). The index is looked up in the current schema, where the ORM’s tables are. - A concurrent index build holds
SHARE UPDATE EXCLUSIVEon its table for as long as it runs: a module operation that alters that table meanwhile waits up to itslock_timeoutand fails withError::LockNotAvailable; run it again once the build is done. - Each step runs with a
statement_timeout(default 6 h,ModuleSystemBuilder::post_commit_statement_timeout), and waits for locks for as long as that (an index build waits for old transactions); the statements between steps use the shortlock_timeout(30 s). A step runs on a connection of its own that is closed afterwards: what it changes in its session (SET ROLE,search_path, an openBEGIN) never reaches another user of the pool. - Steps run in scheduling order. A failed step is reported in the operation’s outcome
(
outcome.post_commit.failed, with the SQLSTATE) and logged, staysfailedand runs again in the next phase;ModuleSystem::pending_post_commit()shows it asPendingState::Failed { step, error, sqlstate }withattempts, the number of runs since it was scheduled. After the third failure the step is parked (PendingState::Parked,PostCommitFailure::parkedin the report): it staysfailedand no phase runs it until an operation schedules it again, so a step that can never succeed does not run after every operation for ever. A row of the queue that no longer passes the checks of scheduling is listed asPendingState::Invalid(a load does not refuse to start for it, and the table’s ownCHECKconstraints refuse most such rows) and a phase marks itfailed, counts the attempt (it parks the same way) and reports it inoutcome.post_commit.invalid. A row another transaction holds locked when the phase wants it (an operation scheduling or removing the step) is reported inoutcome.post_commit.skipped_row_locked, not as superseded. When two phases run together, one runs the steps and the other reportsPostCommitStop::Busy: the running phase reads the queue again until no new step is left (and once more after it releases its lock), so steps an operation commits while another phase runs are not left behind. A phase makes at most 8 passes over the queue (MAX_POST_COMMIT_PASSES) and then stops withPostCommitStop::PassLimitwhen steps keep being scheduled; the rest stay pending. Uninstalling a module removes its steps, and the steps of other modules on a table the uninstall drops. - Work of an install or upgrade that would scan or rewrite a large table (an index build, validating a
foreign key or a not-null constraint, filling a column that becomes required, computing a new stored
computed field) is queued by the operation as schema steps, one row per step, when the table has more rows
than
ModuleSystemBuilder::schema_sync_optionssays (SchemaSyncOptions::large_table_rows, 100,000 by default); smaller tables get the same work inside the operation. The phase plans each step again from the ORM you pass torun_post_commitand the database, so pass the ORM of the current module set. A failed step stays queued and runs again; a batched one resumes after the last batch it committed. - A plain load (
ModuleSystem::load, server start) never runs post-commit steps, also not those its forced update scheduled, so startup never waits for an index build. It lists the steps waiting (LoadOutcome::post_commit_pending: left by an interrupted or skipped phase, failed earlier, or new) and logs a warning with their number; run them withModuleSystem::run_post_commit(&orm), typically in a background task once the server serves.ModuleSystem::pending_post_commit()gives the same list at any time (a health check). Dropping the future of a running phase closes its connection: the statement running there keeps running on the server until it ends (or reaches its timeout), stays pending, and keeps the phase lock until then; a phase started meanwhile reportsPostCommitStop::Busy { holder_pid }naming the backend (pg_stat_activity,pg_cancel_backend). If the dropped future was an operation’s, its outcome is lost although the operation committed: read the module states andpending_post_commit(), and take the ORM fromModuleSystem::load().
let loaded = system.load().await?;if !loaded.post_commit_pending.is_empty() { let system = Arc::clone(&system); tokio::spawn(async move { let report = system.run_post_commit(&loaded.orm).await; if !report.is_clean() { // failed steps and the reason the phase stopped are in the report } });}Module records
Section titled “Module records”The database keeps one ir.module.module row per known addon, with its dependencies
(ir.module.module.dependency), exclusions, category (ir.module.category) and the external ID
base.module_<name>. A row of an installed or scheduled module cannot be deleted (“You are trying to
remove a module that is installed or will be installed.”), and categories cannot form cycles. A module
installed in the database but present in no addon source is reported as unavailable: the registry
loads without it.
Exact numeric admission
Section titled “Exact numeric admission”exact_only = true in manifest.toml opts an addon into exact numeric column admission.
Native addons declare the same value with erp_sdk::addon!(name = "my_addon", exact_only = true);
package describe metadata must agree with the manifest. An absent flag defaults to false for
ordinary addons. Names starting with account or stock, and exact names product and uom,
are always protected; explicitly disabling their flag is an error.
The registry checks the final physical columns after inheritance and related-field composition.
Delegated values are checked at their owning parent column, including a chain of delegates.
A model defined by an exact-only addon is protected model-wide, including columns added later
by ordinary addons or runtime overlays. On an existing model that the addon only extends,
protection applies to fields it declares or redeclares and survives later redeclarations.
Unrelated base columns retain their original policy; a method-only extension does not protect
the whole base model. Exact calculations using an inherited ordinary float require an explicit
conversion rule in the addon’s own spec. Native macro declarations support fixed/named digits
or digits = 0 for unrounded exact decimals. Data-only models/*.toml declarations currently
support fixed numeric digits = [precision, scale]; named and unrounded digit syntax is not
available through that route. Booked monetary amounts keep their Monetary contract. A nonstored field or a JSON column is
not a Float8 column; this admission check does not prove that arbitrary addon code uses no
binary arithmetic.
An admission failure names the protecting addon and declaration, the declaring definition with
its source location, and the physical owning column (including delegated parents). Installation/upgrade stops;
there is no automatic float-to-decimal data conversion. Under ManualFieldPolicy::DropBroken,
an eligible broken manual field is instead omitted and returned in the typed dropped-field report
with DropReason::Refused; its physical column and data remain intact (ADR 0036).
Addon-declared violations still fail under both policies. Review an explicit migration before
redeclaring a populated float column. Shared registry and descriptor identities include the
policy, so enabling it cannot reuse an ordinary-policy registry. The stock SQL constraints and precision-reduction guard are separate integration obligations.
Native data-protection guards during uninstall
Section titled “Native data-protection guards during uninstall”A native addon registers a count-only uninstall guard through erp_sdk::sql_uninstall, with its declared
read tables, static error message and independent manifest. The ORM owns the shared collector/runtime;
ModuleSystem retains owner filtering, lock-first execution and rollback (ADR0249). The legacy framework
namespace remains a reexport for host code. A declaration does not grant request-time System authority.
The module engine locks those tables before taking the destructive transaction’s data snapshot.
A protected row committed while that lock was waiting therefore prevents removal. Positive counts stop
uninstall before its hooks, purge or schema removal; failures leave the installed addon and its data intact.
The same protection applies when a previously scheduled uninstall is consumed during loading.
Guards use the ordinary RepeatableRead ORM lifecycle. Native host composition configures their registration and bounded admission policy; runtime model files cannot introduce guard callbacks or arbitrary SQL. Table locks remain held until commit or rollback. Cancelling a guarded operation closes its held connection so session locks cannot leak into subsequent operations. Lock and statement waits obey the configured module operation timeouts and lower caller limits.
Native SQL functions, triggers and foreign keys are removed restrictively in dependency order, preserving surviving ownership. Unexpected dependencies refuse removal and roll back the complete lifecycle. The confirmed-uninstall planner currently refuses addons with these SQL-object effects or native guards; it does not authorize their removal from a stale preview. Its existing supported ordinary effects retain their confirmation and authorization checks.