Companies in addons: the active companies and company consistency
Status: implemented (ADR 0044, design note docs/design/m3-company.md). Section 1 is the active
companies of an environment, sections 2 to 4 are company-scoped models, what is checked by default
and the messages and cost, section 5 is related fields and section 6 the multi-company hint.
Section 7 is the company_access declaration (ADR 0044 amendment A1, design note
docs/design/m3-company-a1.md).
Every Rust example on this page is compiled as a doctest of erp-test-models.
1. Active companies: env.company(), env.companies() and with_company
Section titled “1. Active companies: env.company(), env.companies() and with_company”An environment has one company context, validated against the companies of the user. It is what
record rules see (company_ids, company_id in an ir.access domain), what company-dependent
cache keys use, and what ir.default and ir.sequence use. There is no second, unchecked copy in
the context: env.company() and a record rule can never disagree.
use erp_orm::{CompanyId, Env};use erp_sdk::Value;
fn report(env: &Env) -> erp_sdk::Result<()> { // the active companies, the current one first; no statement is issued let companies: &[CompanyId] = env.companies()?; // the current company: the first of them let current: Option<CompanyId> = env.company()?; assert_eq!(current, companies.first().copied());
// move company 5 to the front (Odoo's `with_company`); 0 changes nothing let in_five = env.with_company(5)?; // the same through the context let _also = env.with_context([("allowed_company_ids", Value::list([Value::Int(5)]))]); let _ = in_five; Ok(())}Where the companies come from:
| The context says | env.companies() is |
|---|---|
no allowed_company_ids, False or [] | the user’s default order: the main company (res.users.company_id) first, then the others in res.company order (sequence, name, id); archived companies are left out, except an archived main company |
a list [A, B] | exactly that list, in that order (A is current); with_company(C) gives [C, A, B] |
System principal with a list | the list as given (system code names the companies it works for) |
The list is checked against the user’s companies every time the companies are used, not when
the environment is built, as in Odoo, where with_company(x) of a company the user is not in
succeeds and the first read of env.companies fails. Unlike Odoo, sudo() does not skip the
check: an elevated environment is refused the same way, and so is every ORM operation on it
(search, read, write, create, unlink). Code that really works for another company states it with
a principal that is a member (or System); sudo().with_company(other) on a user who is not in
other fails with the error below.
| Mistake | Error |
|---|---|
| a company the user is not in, a list that is not company ids, an archived company | Access: One of the selected companies does not exist or is not one of yours. |
| a company listed twice | Validation: context key 'allowed_company_ids': company 5 is listed twice (the same text the RPC layer returns for a call’s context) |
with_company(-1) | Programming: with_company: invalid company id -1 |
Notes for Odoo developers:
env.companyisenv.company()?andenv.companiesisenv.companies()?; both return aResult, because the check can fail.- A user’s company list is read once per transaction by the principal resolver. If the user loses a
company inside the transaction, the next ORM operation of an environment that still names it
fails with the same
Accesserror. - The resolver installed with
erp_security::resolver::Resolver::for_registry(®istry)orders the companies bysequence,name,idand skips archived ones whenres.companystoresactiveandsequence;Resolver::id_order()does not know the registry and uses the id order. - A duplicate id in
allowed_company_idsis an error here; Odoo accepts it. This is a recorded divergence (ADR 0044, “Lead decisions” in the design note).
2. Company-scoped models and company_match
Section titled “2. Company-scoped models and company_match”A model is company-scoped when it has a stored, not company-dependent many2one company_id to
res.company (scope single), or a stored many2many company_ids to res.company (scope many);
res.company itself is its own scope. Abstract models are never scoped. You write nothing: the
registry finds the scope.
Other records that link to a scoped model must fit its company match, the rule that says which
records of this model a record of company R may use:
company_match | A target is allowed when | Default for | Odoo’s _check_company_domain |
|---|---|---|---|
"exact" | it has no company, or its company is one of R | company_id models | the default [('company_id', 'in', companies + [False])] |
"parent_of" | it has no company, or its company is a company of R or one of their parents | none | check_company_domain_parent_of |
"any_of" | R is empty, or its company_ids meet R | company_ids models (res.users) | the res.users override |
"parent_of_any" | R is empty, or one of its company_ids is a company of R or a parent | none | check_companies_domain_parent_of |
parent_of and parent_of_any need res.company to keep a parent path (parent_store = true
with an indexed parent_path field, as Odoo’s does); a model that asks for them without it makes the
registry refuse to build. A match has to fit the scope (any_of needs company_ids), and
company_match on a model that is not company-scoped is an error too. Those four forms are all
there is: a catalogue shared with the branches of a company is parent_of, a record that lists its
own companies is any_of.
# erp_sdk::addon!(name = "shop");use erp_sdk::prelude::*;
/// A catalogue entry of one company that the company's branches may use as well.#[model(name = "shop.product", description = "Product", company_match = "parent_of")]pub struct Product { #[field(char, required)] pub name: Option<Arc<str>>, #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>,}
/// A record that lists the companies it belongs to (`any_of` is the default for `company_ids`).#[model(name = "shop.channel", description = "Sales Channel")]pub struct Channel { #[field(char)] pub name: Option<Arc<str>>, #[field(many2many, comodel = "res.company")] pub company_ids: Vec<RecId>,}# fn main() {}An unknown value is a compile error (company_match must be one of "exact", "parent_of", "any_of", "parent_of_any"). In a model file (models/*.toml) the same key is spelled the same way, and an
unknown value is an error with the file and line:
[[model]]name = "x_catalogue"company_match = "parent_of"3. What is checked by default, and the two opt-outs
Section titled “3. What is checked by default, and the two opt-outs”In Odoo a link is checked only when the model sets _check_company_auto and the field sets
check_company=True; every flag an author forgets is a silent cross-company link. Here the check is
on by default: a field of a company-scoped model is checked unless it opts out, when
- it is a many2one or many2many, stored (a column or a relation table);
- it is neither computed nor related, not an
_inheritsfield or its delegate many2one, and not one of the four audit fields (create_uid,create_date,write_uid,write_date); - its comodel is company-scoped (so a link to
res.companyitself is not checked, nor a link to a model without a company).
One2many fields are not checked (their lines carry the inverse many2one, which is). A model with at
least one checked field has its check on. The check runs where Odoo’s does: after create, for every
checked field of the new records, and after write, for the written checked fields, or for all of
them when company_id or company_ids is written. It runs under every elevation, sudo() and
System included; it reads company ids without access rules and returns nothing to the caller but
its error.
A company-dependent field is compared with the current company (env.company()), not the record’s;
writing a value of one without a current company is an error that names the field.
The two opt-outs keep Odoo’s behaviour exactly. Use them when a link across companies is the point (an inter-company flow, a shared catalogue kept with a company):
# erp_sdk::addon!(name = "shop");use erp_sdk::prelude::*;
/// Opted out as a whole: no field is checked.#[model(name = "shop.mirror", description = "Mirror", check_company_auto = false)]pub struct Mirror { #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>, #[field(many2one, comodel = "shop.order")] pub source_id: Option<RecId>,}
/// Opted out for one field; the others stay checked.#[model(name = "shop.order", description = "Order")]pub struct Order { #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>, /// Checked: a contact of this order's company, a parent company's, or none. #[field(many2one, comodel = "shop.contact")] pub contact_id: Option<RecId>, /// Not checked: the mirrored order may belong to another company on purpose. #[field(many2one, comodel = "shop.order", check_company = false)] pub mirror_of_id: Option<RecId>,}
#[model(name = "shop.contact", description = "Contact", company_match = "parent_of")]pub struct Contact { #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>,}# fn main() {}In a model file the model-level opt-out is a key of the model, the field-level one a key of the field:
[[model]]name = "x_mirror"check_company_auto = false
[[model.field]]name = "source_id"type = "many2one"comodel = "x_order"check_company = falseWriting check_company (true) on a field, or check_company_auto = true on a model, works as in
Odoo and checks that field even where the default would not. Unlike Odoo, which logs and skips it,
doing so on a model without company_id/company_ids makes the registry refuse to build:
shop.mirror.source_id declares check_company, but shop.mirror has no company_id or company_ids field linked to res.company. Abstract mixins may declare checks; they apply to the models that use
them.
4. Messages and cost
Section titled “4. Messages and cost”An inconsistency is a UserError with Odoo’s text, at most five lines:
These values link records of different companies:- “Order 7” is in company “Company B”, and “Contact” (contact_id: 'Ada') points to a record of another company.- The record is company “Company A”, and “Default Contact” (contact_id: 'Ada') points to a record of another company.Choose records of the same company, or records shared by all companies.The second form is a res.company record (its own company). Targets are shown as Python reprs
('Ada', "O'Neil"). Names are read as the caller: a record or company the caller cannot read
is written shop.contact(12,) instead of its name, so the error cannot be used to read names; Odoo
reads them as superuser. The typed error is erp_sdk::CompanyError (the source of the returned
Error, total counts every inconsistency, also those the text does not list). A linked record that
does not exist is a Missing error: Record does not exist or has been deleted: shop.contact,12 (linked by shop.order.contact_id).
The check reads company ids only for what the transaction cache lacks, in one statement per call (one per 100,000 distinct ids on very large batches) and decides in memory. Values written in the same transaction are in the cache and win over the database, so nothing is flushed for the check, and when everything is cached it costs no statement. Odoo’s check costs two reads per call plus a loop in Python.
| Operation | Odoo 20 | Here |
|---|---|---|
company check of a create/write call, cold cache | 2 reads | at most 1 |
| company check, values cached | 2 reads | 0 |
| a batch of 1,000 rows over several checked fields | 2 reads and 1,000 Python checks | 1 statement |
5. Related fields and companies
Section titled “5. Related fields and companies”A related field reads through records: partner_id.country_id.name. In Odoo such a field is read as
superuser unless it says related_sudo=False, so a user in company A reads a value through a record
of company B without any check. Here a related field that does not declare compute_sudo is
company-bound:
- permissions and non-company rules do not apply to the path, as in Odoo (a salesman still reads the credit limit of the partner through a related field);
- but every record reached through a hop of a company-scoped model must belong to the reader’s
active companies (
env.companies()), by that model’s owncompany_match, or have no company. When the last field of the path is a relational one, the records it points to are one more hop; - a company-bound related field met on the path is followed along its own path with the same bound, so a field cannot reach through another field what the reader could not reach directly;
- a hop outside the active companies fails the read with
Access; there is no silent empty value. A record read ahead with the ones you asked for (the prefetch set) that fails the bound does not fail your read: it stays unread, and raises only when you ask for it.
| Declaration | The path is read | Company check |
|---|---|---|
| nothing (the default) | as superuser for permissions | every company-scoped hop must be in the active companies |
compute_sudo = true | as superuser (Odoo’s default) | none: this is the opt-out |
compute_sudo = false | as the caller (Odoo’s related_sudo=False) | the caller’s own rules decide |
# erp_sdk::addon!(name = "shop");use erp_sdk::prelude::*;
#[model(name = "shop.line", description = "Order Line")]pub struct Line { #[field(many2one, comodel = "shop.order")] pub order_id: Option<RecId>, /// Company-bound: fails when the order belongs to a company outside the active ones. #[field(char, related = "order_id.reference")] pub order_reference: Option<Arc<str>>, /// Odoo's superuser read, for a value every company may see. #[field(char, related = "order_id.reference", compute_sudo = true)] pub order_reference_any: Option<Arc<str>>, /// Read as the caller: the caller's rules decide. #[field(char, related = "order_id.reference", compute_sudo = false)] pub order_reference_mine: Option<Arc<str>>,}
#[model(name = "shop.order", description = "Sales Order")]pub struct Order { #[field(char)] pub reference: Option<Arc<str>>, #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>,}# fn main() {}Reading order_reference of a line whose order belongs to a company the user is not working in
fails with, for example:
You cannot read “Order Reference” (shop.line.order_reference) of Order Line (shop.line: 7): it is read through Sales Order (shop.order: 12), which belongs to a company outside your active companies.
To open the record, switch to its company: Company B.The hop’s id is shown for the first hop only, the one read on the record itself; a hop reached
through another hop is named by its model, since you may not be allowed to see that record. The
second paragraph is the hint of the next section: the company to switch to when it is one of the
user’s, the “no access” note when it is not (a company the user is not in is never named). The
error carries the suggested_company context in the first case.
A label is read the same way: the name shown for a many2one value is the target’s record name, and when that is a company-bound field it is read with your companies, however many links deep the chain goes. If one target fails the bound, the read of the whole set fails with the same error, without the hop’s id (you reached the record through a link and may not read the record behind its hop); the read never substitutes a placeholder name.
A search on a company-bound field that ends on an x2many leaves out every record with a target outside
your active companies (the read of such a record fails, so a search must not find it by one of its own-company
targets or probe the foreign ones). A one-segment related field (related = "partner_id") is bound like the
longer ones: the record it points to counts as a hop.
The registry checks, when it assembles the graph, that a company-bound related field can drop its cached
value when a hop changes company. A path that ends on a relational field that is computed, not stored and
not related is refused (the ORM cannot tell which records to invalidate): store that field, make it related,
or declare compute_sudo on the related field.
What is not bound:
- a
sudo()read and aSystemread keep Odoo’s value (elevation is explicit, and a read for a system job states its company through the principal); - a stored related field is filled at write time and read as any stored column; the write-time consistency check of sections 2 to 4 covers its sources.
Search and group-by on a non-stored company-bound field add the same company condition to each company-scoped hop of the sub-query, so the field cannot be used to learn values of other companies: a search for a value only a foreign hop holds finds nothing, and a group-by puts the records behind a foreign hop into the empty group. A search is still one statement.
Cost. The company of an exact or any_of hop is a column of the row that is fetched for the
hop anyway, so such a read costs the same statements as the compute_sudo = true read of the same
data. A parent_of or parent_of_any hop adds one statement for the active companies’ parent
paths (once per transaction), and a hop scoped by company_ids one for its link rows. The company
of each hop is a dependency of the value: a hop that moves to another company drops the cached
value. The cached value of a company-bound field that goes through a company-scoped hop is kept per set of
active companies (and apart for superuser reads), so a value read for one company context is never
served to another within a transaction.
For Odoo developers: a related field that really must show a value across companies (a partner’s
country, a product’s name on a document of another company) declares compute_sudo = true; every
other related field keeps working in the user’s own companies and fails loudly outside them.
6. The multi-company hint
Section titled “6. The multi-company hint”When a record-level access error is caused by a rule that names the company (a global rule such as
['|', ('company_id', '=', False), ('company_id', 'in', company_ids)], or one that tests
user.company_id), the message ends with Odoo’s multi-company texts, computed from the companies of
the (at most six) denied records:
| The denied records | The message adds |
|---|---|
| belong to several companies | The records belong to several companies: switching the current company may help. |
| belong to one company the user is in | To open the record, switch to its company: Company B. and the error context {"suggested_company": {"id": 2, "display_name": "Company B"}} |
| belong to one company the user is not in | The record belongs to a company outside your allowed companies. The company is never named |
| have no company, or the model has no company field | nothing |
A model with a company_ids field suggests the first of its companies that the user is in
(Odoo’s (company_ids & user.company_ids)[:1]); when there is none, nothing is said.
In the debug listing (an internal user with the technical-features group in debug mode) a record
line carries , company=Company B when the rule names the company and the record’s company is one
of the user’s. Difference from Odoo: the listing shows a record’s display name only when the
record has no company or a company among the user’s active companies; any other record is listed
by model and id (- Sales Order (shop.order: 12, company=Company B)), and its name is never read.
This keeps the error from being a way to read the names of records of other companies. The listing
decides on the record’s own company_id / company_ids: a model without one lists its names, as
Odoo does, so a model whose names must stay inside a company declares its own company field.
The hint costs no statement: the companies of the denied records are read by the one statement that already evaluates the rules on them. The company of a related-field hop (section 5) uses the same texts and context.
7. Company access restrictions
Section titled “7. Company access restrictions”company_match (section 2) says which records a record of company R may link to. Which records
a user may see is a separate declaration: company_access says how the user’s active companies
restrict the model’s records. In Odoo an addon writes this by hand as a global restriction row in
its security file, and nothing notices a model that has none; here the model declares it once, the
registry checks it when it is built, and the restriction row is generated from it.
The registry refuses a concrete company-scoped model without a declaration. A concrete model
without a company field must also make an explicit decision if it has a required, stored many2one
to a company-scoped model. That check does not infer ownership: choose parent(edge = "…") only
when that link is the owner, or unrestricted(reason = "…") when an explicit opt-out is justified.
Optional, company-dependent, non-stored and inherited-copy links do not trigger this check.
The four forms
Section titled “The four forms”| Declaration | Restricts by | Typical use |
|---|---|---|
direct(field = "company_id", branch = …, empty = …) | the model’s own company field (company_id, or company_ids for a model shared between companies) | documents, journals, accounts |
parent(edge = "order_id") | the record that owns it: a stored, required many2one; the record is visible when its owner passes the owner’s company restriction | lines of a document that have no company of their own |
direct(…, parent = "tax_id") | both, ANDed | a child with its own company that must never be shared beyond its owner |
unrestricted(reason = "…") | nothing, said explicitly; the reason (not blank, at most 512 bytes) is listed in reports | a model reached only through another record’s access (a user-type escape is the escape modifier below, not this form) |
branch and empty have no default, so every direct declaration says them:
branch | A record is admitted when its company is |
|---|---|
"exact" | one of the active companies |
"ancestor" | an active company or one of their ancestors (needs res.company to keep its hierarchy) |
empty | A record without company (company_id empty, company_ids empty) is |
|---|---|
"deny" | refused |
"allow" | admitted, while the user has at least one active company |
A nullable company field never implies "allow": write it when you mean it. With
company_ids, a record is admitted when one of its companies matches.
# erp_sdk::addon!(name = "shop");use erp_sdk::prelude::*;
/// A document of one company: users see the documents of their active companies.#[model( name = "shop.order", description = "Order", company_access = direct(field = "company_id", branch = "exact", empty = "deny"))]pub struct Order { #[field(char)] pub name: Option<Arc<str>>, #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>,}
/// A line has no company of its own: it is visible when its order is.#[model( name = "shop.order.line", description = "Order Line", company_access = parent(edge = "order_id"))]pub struct OrderLine { #[field(many2one, comodel = "shop.order", required, ondelete = "cascade")] pub order_id: Option<RecId>,}
/// A catalogue shared with branches, also usable without a company; each price belongs to its/// catalogue entry as well.#[model( name = "shop.price", description = "Price", company_access = direct( field = "company_id", branch = "ancestor", empty = "allow", parent = "order_id" ))]pub struct Price { #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>, #[field(many2one, comodel = "shop.order", required, ondelete = "cascade")] pub order_id: Option<RecId>,}
/// Visible to every company, on purpose.#[model( name = "shop.notice", description = "Notice", company_access = unrestricted(reason = "public notices are shown to every company"))]pub struct Notice { #[field(many2one, comodel = "res.company")] pub company_id: Option<RecId>,}# fn main() {}branch = "ancestor" in that example needs res.company to keep its hierarchy (parent_store
with parent_path); without it the registry refuses the declaration.
The escape: records of one user type are always visible
Section titled “The escape: records of one user type are always visible”Odoo’s partner and user rules admit a record when it passes the company test or belongs to an
internal user. direct(…, escape = "<field>") states that: a record whose own boolean <field> is
false is admitted whatever its companies; any other record takes the company test. The generated
rule is '|', ('<field>', '=', False), <company test>.
company_access = direct(field = "company_id", branch = "ancestor", empty = "allow", escape = "share")The registry refuses the escape unless <field> is a boolean of the model that is stored (a
stored compute is fine, as res.users.share is) and required. Required matters: the negative
boolean test also matches a NULL column, so an optional field would silently admit rows with no
value. A pending recompute of a stored-compute escape is applied before the restricted query of the
same transaction. An extension may drop the escape but never add or change it, and escape cannot
be combined with parent. With an empty active-company set nothing is admitted, escaped records included.
A writable escape lets whoever can write the record make it visible in every company, so declare the
escape on a computed or read-only field. Model files take escape = "share" inside direct = { … }.
Base uses the escape for its two user-facing models, which is the worked example to copy:
| Model | Declaration | Generated rule |
|---|---|---|
res.partner | direct(field = "company_id", branch = "ancestor", empty = "allow", escape = "partner_share") | ['|', ('partner_share', '=', False), '|', ('company_id', '=', False), ('company_id', 'parent_of', company_ids)] |
res.users | direct(field = "company_ids", branch = "exact", empty = "deny", escape = "share") | ['|', ('share', '=', False), ('company_ids', 'in', company_ids)] |
Both escape fields are stored computes declared required with the static default true: a row
that the compute has not reached yet, or that an upgrade filled when the column became NOT NULL,
takes the company test instead of being shown to every company. A static default does
not stop a stored compute without inverse from running after the insert, so the default is only
the fail-closed starting value. share is false for an internal user; partner_share is false for
the superuser’s partner and for a contact with an active internal user. A contact or user of
another company is therefore visible to a restricted user when it belongs to (or is) an internal
user, and otherwise only through the company test. Code that reads contacts or users of other
companies for its own logic (followers, notifications, pickers that must list everyone) reads them
with sudo and states why; a restricted read gets the record-level access error.
Ordinary writes and upsert updates check the resulting generated restriction when they change an escape or any transitive local compute input of it. A refused update poisons the transaction and cannot be committed. This covers the updated records themselves; it does not recheck other records reached through relational compute triggers. Upsert’s existing required-compute/default admission rules still apply before its insert-or-update statement.
Declaring on another addon’s model, and mixins
Section titled “Declaring on another addon’s model, and mixins”#[extend(Model, company_access = …)] declares on a model another addon owns, and an abstract mixin
may declare for the models that inherit it (it is checked on each of them). Declarations compose
through _inherit: the newest is effective, and each later declaration may only narrow the one
before it:
- anything narrows
unrestricted; - on the same field,
"exact"narrows"ancestor"and"deny"narrows"allow"; - adding the other half narrows:
direct(…, parent = "x")narrowsdirect(…)andparent(edge = "x"); - the same owner edge narrows itself.
Everything else is refused: switching between direct and parent, dropping a half,
unrestricted after a restriction, and naming another owner edge (a record has one owner).
_inherits delegation is not inheritance: a delegating model takes nothing from its parent’s
declaration.
# erp_sdk::addon!(name = "shop_strict");# use erp_sdk::prelude::*;# #[model(name = "shop.order", description = "Order",# company_access = direct(field = "company_id", branch = "exact", empty = "allow"))]# pub struct Order {# #[field(many2one, comodel = "res.company")]# pub company_id: Option<RecId>,# }/// A hardening addon: orders without a company are no longer visible.#[extend(Order, company_access = direct(field = "company_id", branch = "exact", empty = "deny"))]pub struct StrictOrder {}# fn main() {}Model files
Section titled “Model files”[[model]]name = "x_contract"[model.company_access]direct = { field = "company_id", branch = "ancestor", empty = "allow" }parent = "partner_id" # with direct: the owner as well; alone: the owner only# unrestricted = "reason" # aloneUnknown keys, a missing field, branch or empty, an unknown branch or empty value and
unrestricted combined with another form are errors with the file and line.
Extending a declared core model
Section titled “Extending a declared core model”The registry refuses a missing required company-access decision. An extension may narrow an
existing core declaration; it cannot widen it. An explicit unrestricted(reason = "…") is an
opt-out and must be justified independently of ordinary model permissions.
What the registry refuses
Section titled “What the registry refuses”When the registry is built (also for model files and per-database overlays), a declaration fails
with a Programming error naming the model and the declaring definition (addon, file and line)
when:
- a direct declaration is on a model without company field, or names another field than the model’s company field;
- it is declared on
res.company(which keeps its own base policy); branch = "ancestor"is used whileres.companykeeps no hierarchy;parent(…)alone is declared on a model that has its own company field (declare both);- the owner edge is not a field, not a many2one, not stored (computed, related, company-dependent,
or a copy from an
_inheritsparent), optional, or links tores.company; - an owner chain ends in a model that is unrestricted, declares nothing, or has no company field; loops back to a model of the chain; or is more than 8 edges deep;
unrestrictedis declared on a model with neither a company field nor a qualifying required stored link to a company-scoped model, or its reason is empty or longer than 512 bytes;- a later declaration widens an earlier one, or names another owner edge.
For example:
shop.order.line: company_access parent(edge = "order_id") names the owner 'order_id', butshop.order.line.order_id is optional: an owner edge is required (required = true), so every recordhas an owner (declared by model definition 'shop.order.line' of addon 'shop' (src/lib.rs:20))A syntax error in #[model(company_access = …)] (an unknown form or parameter, a missing branch
or empty, an empty name, a reason that is blank or longer than 512 bytes) is a compile error on
the offending token.
Generated access rows are not editable addon data
Section titled “Generated access rows are not editable addon data”A row of ir.access marked generated belongs to the model’s
company_access declaration. ORM write and unlink reject these rows,
including archived rows and mixed batches, even under System or sudo().
Explicitly supplying generated to create or write is refused, including
false; addon data files use the same boundary. A default cannot manufacture
an enabled generated marker either.
Use copy() without a generated override to make an ordinary restriction;
generated has copy = false. Ordinary restrictions remain editable and are
combined with generated restrictions by the access engine. Change the model
declaration to change its generated restriction. Lifecycle emission, the tamper
ledger and explicit restoration are planned separately; this protection alone does not install restrictions
or prevent raw SQL from changing the database.
8. Generated restrictions during installation and updates
Section titled “8. Generated restrictions during installation and updates”Every module operation (install, update, uninstall, reinit) ends by writing the company restriction of each
model whose company_access declaration generates one: a group-less, active crud row in ir.access marked
generated. You write nothing; the row follows the declaration.
When upgrading an existing database to these base declarations, update base before serving users.
The update installs the generated restrictions and fills the company hierarchy paths. A missing
generated restriction fails closed; a cycle in the company hierarchy refuses the update. Plan and
verify this database update as part of deployment.
Ledger. ir.model.company_restriction holds the domain text the last operation emitted for the model. The
next operation compares the stored row with it before writing anything.
What an update refuses. If a generated row was deleted, archived, given a group, given another operation or another domain, or if a generated row exists without a ledger entry, the update fails and writes nothing:
Module operation refused: the generated company restriction of <model> (<declaration>) was archived since itwas generated; run the update with --restore-generated-restrictions to rewrite iterp addon update --restore-generated-restrictions (upgrade only) rewrites those rows from the declaration and
lists each one (generated restriction restored: <model>: <what>; programmatically
OperationOutcome::restored_restrictions). Nothing is rewritten unless you pass the flag.
Other refusals.
… the generated company restriction of <model> (<declaration>) <problem>: the read-back after writing did not match the declaration (for example another database trigger altered the row). The operation rolls back.<model> restricts by its owner '<edge>', but N record(s) have no owner: ids …: a model newly restricted through an owner edge has records without an owner (at most 20 ids are listed). Give them an owner, then update again.
Declarations that leave. When a declaration is removed or a model is uninstalled, its generated row and ledger entry go in the same operation. A database that predates generated restrictions has neither; the first update only inserts.
Not here: the ORM refuses to create, archive, change or delete a generated row from code or data files (ir.access
guards); that is a separate protection.
Company branch lifecycle (base 1.5)
Section titled “Company branch lifecycle (base 1.5)”res.company.parent_id is assigned during create and is immutable afterward. Every write containing it fails, including no-op assignments and relational commands that would move an existing branch. Create nested branches with a one2many Create command or an explicit/default parent; do not create a root and reparent it later.
child_ids contains active direct branches. all_child_ids uses inactive-inclusive relation context and contains archived direct branches as well. Neither relation is recursive. The existing company contact creation and mirrored contact fields remain in the normal method chain; default_parent_id is removed from the new contact’s environment.
Missing branch currency inherits from the root; explicit mismatches are validation errors. Root currency writes propagate to every descendant, including archived records. Archive cascades; unarchive does not. Propagated writes use the actor’s ordinary ORM method chain. Addon overrides still run and may refuse; the operation then rolls back atomically. Required inaccessible descendants cause a whole-operation refusal rather than partial propagation.
action_all_company_branches is a read RPC on one existing readable company. It returns list/form current-window navigation with the direct-parent domain, default_parent_id and boolean active_test=false. Authority-bearing context keys remain refused. Modal action context remains defaults-only. The client preserves the initial parent filter when clearing user search.
The private lifecycle row-version fence serializes creation, deletion, archive/currency writes and relevant active-user/default-company transitions. It is PostgreSQL state, not a process lock. Preserve the original retryable serialization error and retry the whole transaction through the established unit-of-work boundary. There is no public skip flag or new delegated-field API. Operation admission is bounded to 256 nested lifecycle entries and 4096 distinct companies.
For binaries linking base, retain .require_core_tables(erp_addon_base::partner_hierarchy::core_tables()); this existing requirement list now covers both partner hierarchy and company lifecycle fences. Publish runtime grants after upgrading base before starting the candidate. See ADR 0137 and the release note for migration and verification status.
Native company-tree queries
Section titled “Native company-tree queries”res.company.root_id is a readonly, nonstored relation to the topmost company (ADR 0225).
Saved-company reads validate the full path against the parent links before returning a root.
Drafts resolve their live parent chain; a parentless draft resolves to itself. Search, grouping
and ordering on this computed relation are refused with its field name; use the stored company
hierarchy for filters. No new database column or migration is needed; update base metadata when
shipping the new native registry.
Native callers can call _accessible_branches on one readable company. It returns the selected
companies reachable through active child edges, using Transaction::companies to validate the
selection. An unselected intermediate parent does not hide its selected descendant; an archived
intermediate parent stops the traversal. The source itself remains eligible even when archived.
Only a core-created System principal without an impersonator may fall back to the source when
there is no intersection. Ordinary elevation does not grant that fallback, and switching a user
to the superuser is refused by the existing principal guard.
_all_branches_selected compares a readable input recordset with the complete active membership
of its roots. Empty input is complete; duplicate identities do not affect the comparison; an
archived input makes it incomplete. The internal completeness query ignores record rules, so a
hidden sibling cannot disappear and make an incomplete selection look complete. It returns only
a boolean. This reveals one fact: an omitted active company exists under a selected root,
possibly one the caller cannot read. No hidden identity or name is returned. Neither helper is
an RPC endpoint, and neither bypasses access checks on later record reads or writes.
All discovery is local to a call and follows flushed ORM state. A subsequent call after a membership change or savepoint rollback rereads that state. These helpers add no configuration, no default records and no separate closure cache. Database state remains authoritative across nodes; existing snapshots keep their transaction isolation.
Company business date
Section titled “Company business date”Use erp_addon_base::company_calendar::business_date(tx, company_id) for effective accounting dates. For a multi-company operation use business_days(tx, env, ids) to read the dates together. Each entry includes the local date and the first valid instant of that date in ERPForAll’s UTC timestamp representation. The instant comes from PostgreSQL’s current transaction. Zone rules come from the base addon’s Jiff timezone database. Supply the caller environment when a service operates on behalf of another principal.
Business dates are resolved from the document’s company, even when a different company is active.
Use the explicit Env argument of business_days when the recordset and transaction principals differ;
business_date uses the transaction environment. The helper authorizes company and timezone-field reads,
flushes pending timezone values, and refuses missing or invalid configuration. Do not replace a refusal
with UTC. The fiscal service uses the same pure conversion after its own company admission because its
separate transaction boundary permits raw SQL only.
Accounting draft and payment dates, undated customer invoices, posting lock decisions, lock-date validation, journal dashboard windows, and stock confirmation share this calendar. Explicit document dates retain their meaning; the posting lock policy may still shift an accounting date. Batch work must resolve each record’s company separately. Audit timestamps remain UTC instants.
Journal dashboards preserve the ancestor-journal access contract: after reading journal fields under the caller’s rights, they may read calendar configuration for those journal companies with elevated record access. Time-zone field permission is still checked as the caller. Ledger figures remain under the caller’s rights; this exception does not grant a general parent-company read.
Account’s company write override invalidates journal dashboard cards when tz changes. A dotted compute dependency would prefetch a parent company under the branch reader before the narrow metadata admission, so the dashboard deliberately does not declare that path. Native SQL writers that change tz must also invalidate account.journal’s dashboard_card cache in the same transaction.