Skip to content

[InterCompany] Disable feature-specific indexes for tenants who don't use it - #14818

Open
dcenic wants to merge 8 commits into
mainfrom
features/661822InterCompanyIndexes
Open

dcenic wants to merge 8 commits into
mainfrom
features/661822InterCompanyIndexes

Conversation

@dcenic

@dcenic dcenic commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

What & why

G/L Entry, Customer and Vendor each have a non-unique key on "IC Partner Code" that only intercompany (IC) code reads. Every company still maintains these indexes, even though most never use IC. G/L Entry is the costly one: it's large and insert-heavy, and the column is almost always empty.

This change turns these indexes off at runtime, through the platform's Index Management codeunit, in companies that don't use IC. It turns them back on as soon as a company starts using IC:

  • Existing companies (upgrade): a new per-company upgrade step turns the indexes off if the company has no IC partners. It runs IC Partner.DisableICPartnerCodeIndexesIfICNotUsed(), guarded by the upgrade tag MS-661822-DisableICPartnerCodeIndexes-20261202. The only check is IC Partner.IsEmpty(); the code deliberately doesn't filter G/L Entry, Customer or Vendor on "IC Partner Code", because that would be expensive on large tables (a full scan if the index is already off). Checking IC Partner alone is enough: the "IC Partner Code" fields relate to IC Partner, deleting an IC partner clears the code on G/L Entries and is blocked while a customer or vendor is linked, and every code path that reads these indexes starts from an existing IC partner.
  • New companies and new tenants: nothing happens at company initialization. The upgrade tag is deliberately not registered in OnGetPerCompanyUpgradeTags, so company initialization doesn't mark it as done, and the upgrade step handles each new company at the next upgrade. Company initialization is a critical path, and turning an index off isn't cheap: per table it reads Database Index (catalog views plus sys.dm_db_index_physical_stats), takes a tenant-level app lock (up to 30 s wait), runs DROP INDEX, writes the index state, and invalidates the index-override cache on all server instances. Until the next upgrade, a new company keeps the indexes, but its tables are small then, so the indexes cost little to maintain and are cheap to drop. Companies created with Copy Company inherit the source company's index state (CopyCompanyOverrides in the platform).
  • Company starts using IC: when the first IC partner is created, a new OnAfterInsertEvent subscriber on IC Partner (in codeunit 489 IC Partner Change Monitor) calls IC Partner.EnableICPartnerCodeIndexesIfFirstICPartner(), which calls Index Management.EnableKey for any of the three indexes missing from Database Index for the current company. This only queues the index; the platform builds it in the next maintenance window. Later IC partners skip this with one IsEmpty on the other partners, because the indexes are then already on or queued. The Database Index check itself is needed: EnableKey isn't a no-op for an index that already exists, because the maintenance job (EnableSingleIndexAsync) drops and recreates it. A table event is used instead of the OnInsert trigger so that inserts that skip table triggers, such as configuration package imports with Skip Table Triggers, also turn the indexes back on.

Every company that takes part in IC, on the sending or receiving side, must have an IC Partner record for the other company. Database delivery fails with ICPartnerMissingCurrentCompanyErr without it, and accepting inbox documents calls ICPartner.Get. So inserting an IC partner reliably signals that a company uses IC.

Implementation notes:

  • Keys are found by field, not by name. Key names differ between localizations (G/L Entry uses Key8 in W1 but Key9 in BE and FI). The code finds the single-field, non-unique BaseApp key on "IC Partner Code" using RecordRef/KeyRef.
  • The AL keys stay enabled. There's no Enabled = false in the metadata, so admins can still turn these indexes on or off from Table Information, and the schema doesn't change.
  • No [TryFunction]. The upgrade step and the IC Partner insert run in write transactions, so the calls are direct. Each call is guarded by a check that the key exists and that the index isn't already in the target state.
  • Permissions: the IC Partner table gets an indirect read on Database Index, as the System Application's Table Information pages have.
  • Telemetry: no custom telemetry. The platform already logs LC0063 (index enabled at runtime) and LC0064 (index disabled at runtime) for Index Management calls.
  • Country layers: the upgrade changes are copied to the country-specific UpgradeBaseApp (AT, BE, CH, IT, NL, NO, RU) and UpgradeTagDefinitions (BE, IT, RU) files.

Reviewers from Server Runtime, please confirm:

  1. IndexManagement.DisableKey can be called inside the per-company upgrade transaction, and the tenant-level app lock it takes (up to 30 s wait) is acceptable there.
  2. Indexes turned off this way stay off across later app upgrades and schema syncs. From the platform code, ApplyIndexOverrideState in CreateNonSiftIndexes seems to ensure this.
  3. Checking Database Index (Get with the name from GetKeyIndexName, plus Enabled) is the right way to tell whether an index currently exists for a company. TryGetByPrimaryKey also runs sys.dm_db_index_physical_stats to fill in Fragmentation. Is there a cheaper way from AL to read the runtime enabled state? Key.Enabled only returns the metadata value.

Linked work

Fixes AB#661822

How I validated this

  • I read the full diff and it contains only changes I intended.
  • I built the affected app(s) locally with no new analyzer warnings.
  • I ran the change in Business Central and confirmed it behaves as expected.
  • I added or updated tests for the new behavior, or explained below why none are needed.

What I tested and the outcome (required — be specific: scenarios, commands, screenshots for UI changes)

  • AL language server diagnostics for all four changed W1 files: 0 errors, 0 warnings.
  • al_build for W1 BaseApp: failed because of errors already in my local workspace (missing DotNet references and outdated System symbols, for example Uri.IsHttpUrl). None of the errors are in the changed files. CI will do the full compile, including the country layers.
  • Not yet run in Business Central. These still need checking in a container:
    • Upgrading a company with no IC partners turns the three indexes off. A company with IC partners keeps them.
    • A company created after the upgrade keeps the indexes, and the next upgrade turns them off.
    • Inserting the first IC partner queues them to be turned on, including with Insert(false), and a user who isn't an admin can still create an IC partner.
  • No automated tests added: whether an index is turned off or on depends on Database Index, which reads SQL Server's index metadata, and on the nightly maintenance run, so the result can't be checked in a unit test. SetCurrentKey("IC Partner Code") only adds an ORDER BY, so IC code works the same while an index is off.

Risk & compatibility

  • Upgrade and data: no data changes and no schema changes. The upgrade only turns indexes off in companies with no IC partners (one IsEmpty on IC Partner), and it's guarded by an upgrade tag.
  • Performance for companies that start using IC: until the nightly maintenance run builds the indexes, IC queries filter on "IC Partner Code" without an index. That affects posting IC documents, the IC Transactions report and deleting an IC partner.
  • Partner extensions that rely on these indexes for their own queries may get slower in companies that don't use IC. Admins can turn the indexes back on from Table Information.
  • Permissions: inserting an IC partner now reads Database Index (granted indirectly by the table) and calls Index Management.EnableKey.
  • Telemetry: none added. Use the platform events LC0063 and LC0064 to monitor which indexes are turned on and off.

… use it

Turn off the indexes on the IC Partner Code field of G/L Entry, Customer and Vendor in companies that don't use intercompany (upgrade and company initialization), and queue them to be turned on again when an IC partner is created.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@dcenic
dcenic requested a review from a team December 2, 2026 12:16
@dcenic
dcenic requested a review from a team as a code owner December 2, 2026 12:16
@github-actions github-actions Bot added the Team: Finance GitHub request for Finance area label Dec 2, 2026
@github-actions github-actions Bot added this to the Version 30.0 milestone Dec 2, 2026
dcenic and others added 5 commits December 2, 2026 13:20
…ndexes

Filtering G/L Entry, Customer and Vendor on IC Partner Code is expensive on large tables, and an empty IC Partner table is a sufficient signal.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The platform already emits LC0063 and LC0064 when Index Management enables or disables a key.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Company initialization is a critical path. Turning an index off reads Database Index (catalog and DMV queries), takes a tenant lock, runs DDL and invalidates the index override cache, so it now runs in a task scheduled from OnCompanyInitialize in the new codeunit 438 IC Partner Code Indexes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…esn't run

Don't register the upgrade tag as a per-company tag, and set it from the background task instead, so that companies where the task couldn't be created or failed are handled by the upgrade code.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ization

Remove the OnCompanyInitialize background task and codeunit 438. The upgrade tag isn't registered as a per-company tag, so the upgrade step handles new companies at the next upgrade, while their tables are still small.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@dcenic
dcenic enabled auto-merge December 2, 2026 13:27
…reated

EnableKey isn't a no-op for an index that already exists (the maintenance job drops and recreates it), so the Database Index check is needed, but only the first IC partner can find the indexes turned off.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@alexei-dobriansky

Copy link
Copy Markdown
Contributor

Good Sense Reviewer - Round 1

Recommendation: Accept with Suggestions

What this PR does

Turns off three IC Partner Code indexes in companies without IC partners during upgrade, then queues them for rebuilding when the first partner is inserted. This reduces unused index maintenance, especially on G/L Entry.

The eight upgrade implementations and four upgrade-tag definitions are consistent. Key lookup accounts for localization differences, existing IC companies retain their indexes, and new companies are deliberately handled at their next upgrade. Normal partner insertion restores the indexes, but inserts that skip table triggers bypass that restoration.

Problem-solution fit

Fit: Partial

The change targets the intended index overhead without changing financial records or key metadata. Automatic restoration does not cover importing the first IC partner with table triggers skipped.

Suggestions

S1 (🟠 Moderate): Re-enable indexes when insert triggers are skipped
Run the re-enable logic from an insert event that also runs when RunTrigger is false. Importing the first IC partner with Skip Table Triggers leaves the indexes disabled, and later partner inserts skip the check because a partner already exists.

Risk assessment and necessity

Risk: The changed paths affect per-company upgrades and initial IC setup, not amounts, ledger contents, or existing public signatures. Rebuilding is delayed until maintenance, so IC queries can temporarily run without these indexes; trigger-skipping imports can leave that state in place indefinitely. No builds or tests were run for this review. Runtime permissions, upgrade-transaction support, on-premises queue processing, and persistence across later schema syncs remain unverified; none is established here as a defect.

Necessity: Companies without IC otherwise keep paying write and storage costs for unused indexes. The three-index scope is focused, and retaining the AL keys lets administrators restore indexes needed by extensions.


[AI-PR-REVIEW] version=1 promptVersion=4 system=github pr=14818 round=1 by=alexei-dobriansky at=2026-12-02T20:30:22Z lastSha=bd8262d6758d777b7b65294308db78493ad8b3dc reviewKey=f673cbdc21a2f9684a96c87dd96d17022697bc53e339867c60448edfd6c1b485 suggestions=S1@49ca1a63

…serted without table triggers

Move the logic from the IC Partner OnInsert trigger to an OnAfterInsertEvent subscriber in IC Partner Change Monitor, so that inserts with RunTrigger = false (for example, configuration package imports) are covered. Also fix the AA0021 variable order warning that failed the builds.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@alexei-dobriansky

Copy link
Copy Markdown
Contributor

Good Sense Reviewer - Round 2

Recommendation: Accept

What this PR does

Turns off three IC Partner Code indexes during upgrade in companies without IC partners, then queues them for rebuilding when the first partner is inserted. This reduces unused index maintenance, especially on G/L Entry.

This update moves restoration from OnInsert to OnAfterInsertEvent, covering inserts that skip table triggers. The helper excludes the inserted partner when checking for other partners and still exits for temporary records. The eight upgrade implementations and four upgrade-tag definitions remain consistent.

Problem-solution fit

Fit: Strong

The change targets unused index overhead without changing financial records or key metadata. The previous restoration gap for imports that skip table triggers is now closed; newly created companies remain deliberately deferred until their next upgrade.

Status of previous suggestions
ID Title Status Author response
S1 Re-enable indexes when insert triggers are skipped Addressed da9be3d moves restoration to OnAfterInsertEvent without a RunTrigger guard and retains the temporary-record exit.
New observations (commits since round 1)

None — the update addresses the previous suggestion and corrects variable ordering.

Risk assessment and necessity

Risk: The changed paths affect upgrades and initial IC setup, not amounts, ledger contents, or existing public signatures. First-partner imports now queue index work too, and IC queries may scan until maintenance rebuilds the indexes. Ordinary-user permissions, upgrade-transaction support, on-premises queue processing, and persistence across later schema syncs remain unverified; none is established here as a defect. No builds or runtime tests were run for this review.

Necessity: Companies without IC otherwise keep paying write and storage costs for unused indexes. The three-index scope is focused, and retaining the AL keys lets administrators restore indexes needed by extensions.


[AI-PR-REVIEW] version=1 promptVersion=4 system=github pr=14818 round=2 by=alexei-dobriansky at=2026-12-03T14:21:35Z lastSha=da9be3d9eaafbe74fa2bcd52319b5d4fd138eb67 reviewKey=5caf9cc3302d52dcdfe90f20b4cbd57a73bf157b9a4f5fae7eec81872841644c suggestions=S1@49ca1a63:addressed parentRound=1

This branch was previously deployed

1 inactive (outdated) deployment
triage — 8528402d Deployed Dec 2, 2026 by dcenic via Classify team ownership #12698
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Team: Finance GitHub request for Finance area

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants