# Setting up a custom namespace

Custom namespaces serve as logical environments to package and isolate your data
foundation and analytical data product modules. Running inside a dedicated
custom namespace lets you manage configuration and deployment options
independently, providing isolation for your environment. A key benefit of this
separation is that you can pull future updates and enhancements from the
`cortex` namespace in Google Cloud Cortex Framework without overriding or corrupting
your custom modules. Create your custom modules within a dedicated namespace.

> [!NOTE]
> **Note:** One namespace can contain multiple data foundation and data product modules.

## Custom namespace folder structure

The Cortex Framework namespace folders package and isolate custom
module artifacts as Python implicit namespace packages.

The folder structure of a custom namespace is defined in the following table:

| Directory path | Purpose and description |
| `config/` | **Cortex deployment configuration** (Required) Registers custom namespaces and modules in `config.yaml` (or another named configuration file). |
| `src/data_modules/CUSTOM_NAMESPACE/SYSTEM_TYPE/foundations/DATA_FOUNDATION_MODULE_NAME/` | **Data foundation modules** Raw-to-foundation dataset transformations. Each data foundation resides in its own leaf directory (no Python files inside content blueprint folders) and consists of: - `manifest.yaml`: Declares the module `category` (`foundation`) and `builder`. The leaf directory name identifies the module automatically. - `annotations/`: Column and field-level descriptions. - `table_settings.default.yaml`: Default [table settings](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#config-table-settings-yaml) configuration. - `assertions/`: *Optional.* Module-scoped custom SQL assertion templates. |
| `src/data_modules/CUSTOM_NAMESPACE/SYSTEM_TYPE/products/DATA_PRODUCT_MODULE_NAME/` | **Data product definitions** Contains business logic and analytical models. Each product resides in its own leaf directory (no Python files inside content blueprint folders) and consists of: - `README.md`: Documentation of the module. - `manifest.yaml`: Declares the module `category`, `builder`, and upstream `dependencies`. - `table_settings.default.yaml`: Default [table settings](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#config-table-settings-yaml) configuration. - `annotations/`: Column and field-level descriptions. - `definitions/`: Dataform JavaScript (`.js`) definitions using `publisher.publish()` (recommended over `.sqlx`). - `assertions/`: *Optional.* Module-scoped custom SQL assertion templates. |
| `src/data_modules/CUSTOM_NAMESPACE/includes/` | **Shared JavaScript helpers** Shared Dataform JavaScript helpers live strictly at the namespace root (`<namespace>/includes/*.js`, with no nested or blueprint-local `includes/` directories) and are copied directly into `dist/includes/` during compilation (`require("includes/<file>.js")`). Prefix shared helper filenames with your namespace (for example, `acme_helpers.js`) to prevent collisions across modules. |
| `src/data_modules/CUSTOM_NAMESPACE/assertions/` | **Shared SQL assertion templates** Reusable custom SQL assertion templates shared across all modules in the namespace. Cortex Framework enforces a two-boundary layout for `assertions/`: templates live either at the namespace root (`<namespace>/assertions/`) or inside a leaf blueprint directory (`<module_dir>/assertions/`), with no intermediate segment directories. |
| `src/data_modules/CUSTOM_NAMESPACE/{builders,schemas,metadata}/` | **Root-anchored Python SDK plugins** (Optional) All Python plugin code for a namespace lives strictly in these three root-anchored directories with zero `__init__.py` files anywhere under the namespace: - `builders/`: Custom `FoundationBuilder`, `FlatProductBuilder`, `VersionedProductBuilder`, or `CatalogBuilder` subclasses importing from `common.sdk`. - `schemas/`: Pydantic v2 models for `moduleSettings` and `table_settings.yaml` (must not import `metadata`, `builders`, or Google Cloud client libraries). - `metadata/`: Runtime `MetadataProvider` implementations imported lazily by builders inside runtime methods. Pure-content namespaces (such as `cortex_samples`, `cortex_v6_compatibility`, or custom content-only namespaces) require zero Python files and reference built-in SDK builders directly. |
|---|---|

Replace the following:

- `CUSTOM_NAMESPACE`: the name of your custom namespace directory under `src/data_modules/`, for example: `sap_bookingdatamodel` or `acme_corp`.
- `SYSTEM_TYPE`: the source system or domain folder name, for example: `sap` or `ticketing`.
- `DATA_FOUNDATION_MODULE_NAME`: the leaf directory name of your custom data foundation module, for example: `ticketing_system`.
- `DATA_PRODUCT_MODULE_NAME`: the leaf directory name of your custom data product module, for example: `flights_usd` or `sales_performance`.

## Custom namespace configuration

You can define a new namespace
(`CUSTOM_NAMESPACE`) by extending the
corresponding section of the `config.yaml` file, creating a new directory under
`src/data_modules/`, and adding the new module code assets.

To make the Cortex Framework compiler aware of your custom
namespace and modules, register them in your global configuration file (for
example, `config/config.yaml`).

### Register the namespace

Under `data.namespaces`, list each namespace you want active in the workspace.
Omit `path` for built-in namespaces (`cortex`, `cortex_samples`,
`cortex_v6_compatibility`) and installed third-party `cortex.namespaces` wheel
packages; specify `path` only for local custom namespaces or local override
overlays:

```yaml
data:
  namespaces:
    - name: cortex
    - name: CUSTOM_NAMESPACE   # Name of custom namespace
      path: ../src/data_modules/CUSTOM_NAMESPACE  # Relative to config.yaml directory
```

Replace the following:

- `CUSTOM_NAMESPACE`: the name of your custom namespace directory under `src/data_modules/`, for example: `acme_corp` or `sap_bookingdatamodel`.

Cortex Framework applies the following rules when resolving
`data.namespaces`:

- **Built-in and wheel-installed namespaces** : Omit `path` (`- name: cortex`, `- name: cortex_samples`, `- name: cortex_v6_compatibility`, or an installed third-party extension wheel such as `- name: partner_erp`). Setting `path` to the shipped built-in namespace directory (or a missing legacy `src/data_modules/<builtin>` path) emits a `DeprecationWarning` and isn't portable to wheel installations. Pointing `path` to a separate local override directory is supported for multi-root override stacking.
- **Local custom namespaces** : Always specify `path` (relative to the configuration file directory) for local custom namespaces---even when the directory sits next to shipped namespaces under `src/data_modules/` in a source checkout---so the same `config.yaml` works consistently against wheel installations.
- **Strict allowlist versus auto-discovery** :
  - When `data.namespaces` is present as a list, it acts as a **strict
    allowlist** : only listed namespaces are indexed by `ModuleCatalog` and permitted for `<pkg.mod>:<Class>` builder imports. Setting `namespaces: []` is a valid empty allowlist.
  - Omitting the `namespaces` key entirely enables auto-discovery of all installed built-in and `cortex.namespaces` packages.
  - Setting `namespaces: null` (for example, leaving the `namespaces:` key with every list item commented out) is rejected at validation time.
- **Multi-root override stacking** : To overlay local changes on top of an
  installed namespace, list multiple entries for the same `name` in priority
  order (highest precedence first). For example:

  ```yaml
  data:
    namespaces:
      - name: cortex
        path: ../local_overrides/cortex
      - name: cortex
  ```
- **Reserved names** : Namespace names must be valid Python identifiers and
  can't use Python keywords, Python standard-library or built-in module names,
  reserved Cortex Framework internal package names (`common`,
  `tools`, `data_modules`, `dataform_includes`, and `tests`), or installed
  third-party top-level Python packages (for example, `google`, `yaml`, or
  `pydantic`) unless that package registers the namespace through a
  `cortex.namespaces` entry point.

### Configure custom modules

Register your custom modules under `data.modules.foundations` or
`data.modules.products`. Use the dot-separated `modulePath` starting with your
namespace name (by convention, the four-segment format
`<namespace>.<system_type>.{foundations|products}.<module_name>`). Each
`dataSourceId` and `dataTargetId` value must match an `id` entry defined in the
[`data.datasets` list](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#bigquery-sources-and-target-datasets)
in `config.yaml`. Don't set the deprecated `moduleType` field in `config.yaml`:

```yaml
data:
  modules:
    foundations:
      - moduleId: CUSTOM_NAMESPACE_DATA_FOUNDATION_MODULE_NAME
        modulePath: CUSTOM_NAMESPACE.ticketing.foundations.DATA_FOUNDATION_MODULE_NAME
        dataSourceId: ticketing_data_raw
        dataTargetId: data_foundation_ticketing
        # Optional custom table settings file relative to 'config/'
        # (replaces table_settings.default.yaml):
        # tableSettings: "CUSTOM_NAMESPACE/ticketing/foundations/DATA_FOUNDATION_MODULE_NAME/table_settings.yaml"

    products:
      - moduleId: CUSTOM_NAMESPACE_DATA_PRODUCT_MODULE_NAME
        modulePath: CUSTOM_NAMESPACE.ticketing.products.DATA_PRODUCT_MODULE_NAME
        dependencyBindings:
          # References an existing foundation moduleId
          ticketingModule: CUSTOM_NAMESPACE_DATA_FOUNDATION_MODULE_NAME
        dataTargetId: product_target
        # Optional sparse custom table settings override relative to 'config/':
        # tableSettings: "CUSTOM_NAMESPACE/ticketing/products/DATA_PRODUCT_MODULE_NAME/table_settings.yaml"
```

Replace the following:

- `CUSTOM_NAMESPACE`: the name of your custom namespace, for example: `ticketing` or `acme_corp`.
- `DATA_FOUNDATION_MODULE_NAME`: the leaf directory name of your custom data foundation module, for example: `ticketing_system`.
- `DATA_PRODUCT_MODULE_NAME`: the leaf directory name of your custom data product module, for example: `ticket_metrics` or `sales_performance`.

Custom foundation modules support source systems without a prebuilt builder
(such as PostgreSQL) and require a custom `FoundationBuilder` subclass in
`<namespace>/builders/`. For a walkthrough, see
[Data foundation module creation](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-foundation.md.txt).
Because `sap_foundation` and `sfdc_foundation` are scoped to `cortex`, don't
create a custom foundation module for SAP ERP or Salesforce. Instead, register a
[separate instance of the prebuilt foundation module](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#multiple-data-foundation-instances)
(`cortex.sap.foundations.sap` or `cortex.sfdc.foundations.sfdc`) and bind your
custom data product to its `moduleId` in `dependencyBindings`.

> [!NOTE]
> **Note:** The `DATA_FOUNDATION_MODULE_NAME` and `DATA_PRODUCT_MODULE_NAME` values are lowercase `snake_case` strings matching the leaf directory name containing `manifest.yaml`. Don't set `type:` inside `manifest.yaml`; it is deprecated in version 7.1 and ignored because the leaf directory name identifies the module automatically.

## Custom namespace shared code

A custom namespace supports sharing code artifacts across its modules while
enforcing clean architectural boundaries:

- **`includes/` (`<custom_namespace>/includes/*.js`)** : JavaScript helpers staged into `dist/includes/` during compilation (`require("includes/<file>.js")`) and discovered automatically through `ModuleBuilder.get_includes_dirs()`. Prefix shared filenames with your namespace (for example, `acme_helpers.js`) to prevent collisions.
- **`assertions/` (`<custom_namespace>/assertions/*.sql`)** : Reusable SQL assertion templates discovered automatically through `ModuleBuilder.get_shared_assertion_dirs()`. Module-specific templates can also live inside a leaf blueprint directory (`<module_dir>/assertions/`).
- **`builders/`, `schemas/`, and `metadata/`** : Root-anchored Python Plugin SDK extensions (`<custom_namespace>/{builders,schemas,metadata}/`) with zero `__init__.py` files anywhere in the namespace. Import framework symbols exclusively from `common.sdk` (never `common.registry` or internal `common.builders.*` modules), keep `schemas/` free of `metadata`, `builders`, and Google Cloud client imports, and import metadata providers and `google.cloud.bigquery` lazily inside runtime methods to preserve offline workspace resolution.

## Understand and reference builders

Builders are Python classes that compile resolved workspace nodes into
Dataform outputs. Cortex Framework uses deterministic
`ModuleCatalog` and `BuilderResolver` discovery---without import-side-effect
registries (`common.registry` was removed in version 7.1)---to resolve the
`builder:` value in each module's `manifest.yaml`.

### Builder resolution precedence

`BuilderResolver` resolves `manifest.yaml` `builder:` references in the
following order from highest to lowest precedence:

| Precedence | Source or syntax | Description |
| 1 | In-memory `PluginOverrides` | `PluginOverrides(builders=..., catalog_builders=...)` supplied programmatically by tests or embedded callers. |
| 2 | Explicit class reference (`<pkg.mod>:<Class>`) | Imports a specific class from the current namespace (for example, `partner_erp.builders.custom_product:CustomProductBuilder`) or a registered `cortex.builders` entry-point module. Cross-namespace references (`<other_ns>.*:<Class>`) are rejected. |
| 3 | Same-namespace qualified (`<current_ns>.<name>`) | Matches `plugin_id` or `plugin_aliases` in `<current_ns>/builders/` (for example, `partner_erp.custom_product`). Cross-namespace references (`<other_ns>.<name>`) are rejected. |
| 4 | Blueprint-local `./builder.py` *(Deprecated)* | Legacy co-located `<module_dir>/builder.py`. Emits a `DeprecationWarning` and is scheduled for removal in version 8.0. |
| 5 | Namespace-scoped shared builders (`<current_ns>/builders/*.py`) | Matches unqualified `<name>` against `plugin_id` or `plugin_aliases` across the current namespace's mounted roots in priority order. |
| 6 | Built-in SDK builders and `cortex.builders` entry points | Matches unqualified `<name>` against the three built-in SDK product builders (`flat_product`, `versioned_product`, `sap_product`) and installed third-party `cortex.builders` Python entry points. |
|---|---|---|

### Built-in SDK builders and namespace scoping

Only three built-in SDK module builders are available globally to **any** custom
namespace:

| `builder` value (`plugin_id`) | SDK class (`common.sdk`) | Intended use |
| `flat_product` | `FlatProductBuilder` | Flat `definitions/*.js` data products with flat top-level `FlatProductTableSettings` (custom-namespace Salesforce products, SAP Business Data Cloud Delta Sharing products, custom-source products, and multi-source composite products). Set `materializationType` explicitly on each table. |
| `versioned_product` | `VersionedProductBuilder` | Variant-sectioned data products (`common:` plus `<variant>:`) that overlay `definitions/<active_variant>/` atop `definitions/common/` and infer supported variants automatically from table settings, definition subfolders, and manifest dependencies. |
| `sap_product` | `SapProductBuilder` | SAP ECC and SAP S/4HANA versioned data products (`SapProductTableSettings`) shared across `cortex`, `cortex_samples`, `cortex_v6_compatibility`, and custom namespaces. |
|---|---|---|

Keep the following scoping and deprecation boundaries in mind when selecting a
builder:

- **`sfdc_product` is scoped to `cortex` (not global)** : `SfdcProductBuilder` lives in `cortex/builders/sfdc_product_builder.py`. Because `BuilderResolver` rejects cross-namespace builder references, custom namespaces building or extending Salesforce data products must use `builder: flat_product` (with explicit `materializationType` on each table). Similarly, `sap_foundation` and `sfdc_foundation` are scoped to `cortex`.
- **External catalog builders are `CatalogBuilder` plugins** : `lakehouse_delta_share` and `analytics_hub` are configured using `type:` under `data.modules.catalogs` in `config.yaml`, not as `builder:` values in a module's `manifest.yaml`.
- **Deprecated aliases and legacy paths (removed in version 8.0)** :
  - Legacy product builder aliases `generic_product`, `composite_product`, `generic_composite_product`, and `sap_bdc_product` emit a `DeprecationWarning`. Migrate to `builder: flat_product` and set `materializationType` explicitly on each table (note that `sap_bdc_product` is a legacy alias of `flat_product` and no longer defaults to `view`).
  - Blueprint-local `./builder.py` files (omitting `builder:` in `manifest.yaml`) and nested `<namespace>/<segment>/builders/` directories (including `<namespace>/common/builders/`) emit a `DeprecationWarning`. Move custom builders to `<namespace>/builders/` and declare `plugin_id`.

For example, to use the built-in SAP data product builder in your custom
namespace, reference `sap_product` in `manifest.yaml`:

```yaml
# src/data_modules/CUSTOM_NAMESPACE/sap/products/DATA_PRODUCT_MODULE_NAME/manifest.yaml
displayName: Custom SAP Data Product
description: Custom SAP analytical data product.
category: consumption_product
builder: sap_product
dependencies:
  sapModule:
    modulePath: cortex.sap.foundations.sap
    supportedVersions:
      - ecc
      - s4
    tables:
      common:
        - kna1
```

Replace the following:

- `CUSTOM_NAMESPACE`: the name of your custom namespace, for example: `sap_bookingdatamodel` or `mycompany`.
- `DATA_PRODUCT_MODULE_NAME`: the leaf directory name of your custom data product module, for example: `flights_usd`.

### Namespace-scoped custom builders

If modules inside your custom namespace require a specialized compiler, declare
a builder plugin using the Tier 3 Python Plugin SDK (`common.sdk`):

1. Create a builder file under `src/data_modules/<custom_namespace>/builders/my_builder.py` (keeping zero `__init__.py` files anywhere under `src/data_modules/<custom_namespace>/`).
2. Subclass `FlatProductBuilder`, `VersionedProductBuilder`, or
   `FoundationBuilder` from `common.sdk` and set `plugin_id` (with optional
   `plugin_aliases`, `legacy_aliases`, `module_settings_schema_cls`, and
   `table_settings_schema`):

   ```python
   # src/data_modules/acme_corp/builders/finance_product_builder.py
   from typing import ClassVar
   import pydantic

   from common.sdk import (
       CortexBaseModel,
       FlatProductBuilder,
       FlatProductTableSettings,
   )

   class FinanceProductSettings(CortexBaseModel):
       reporting_currency: str = pydantic.Field(alias="reportingCurrency")
       fiscal_year_start_month: int = pydantic.Field(
           default=1, alias="fiscalYearStartMonth"
       )

   class AcmeFinanceProductBuilder(FlatProductBuilder):
       plugin_id: ClassVar[str | None] = "acme_finance_product"
       module_settings_schema_cls = FinanceProductSettings
       table_settings_schema = FlatProductTableSettings
   ```
3. Reference the builder in your module's `manifest.yaml` using
   `builder: acme_finance_product` (or same-namespace qualified
   `builder: acme_corp.acme_finance_product`, or explicit
   `builder: acme_corp.builders.finance_product_builder:AcmeFinanceProductBuilder`).

### Package plugins as Python wheels and test with `PluginOverrides`

To share reusable namespaces or standalone builders across multiple repositories
without copying files under `src/data_modules/`, publish a standard Python wheel
declaring `cortex.namespaces` or `cortex.builders` entry points in
`pyproject.toml`:

```toml
[project.entry-points."cortex.namespaces"]
partner_erp = "partner_erp_pkg:get_namespace_root"

[project.entry-points."cortex.builders"]
acme_product = "acme_cortex.builders:AcmeProductBuilder"
```

- A `cortex.namespaces` entry point can resolve to a `pathlib.Path` or `str` directory, a zero-argument callable returning a path, or an imported package with `__path__`. After installing the wheel, activate the namespace in `config.yaml` without `path` (`- name: partner_erp`), or omit `data.namespaces` to auto-discover installed packages.
- A `cortex.builders` entry point registers a standalone `ModuleBuilder` or `CatalogBuilder` subclass directly under its entry-point name.

For unit tests or embedded invocations, use `PluginOverrides` from `common.sdk`
to inject builders at the highest resolution precedence without writing files or
registering entry points:

```python
from common.sdk import PluginOverrides

overrides = PluginOverrides(
    builders={"custom_product": MyCustomProductBuilder},
    catalog_builders={"custom_catalog": MyCustomCatalogBuilder},
)
```

> [!NOTE]
> **Note:** Blueprint-local `<module_dir>/builder.py` files (omitting `builder:` in `manifest.yaml`) and `<namespace>/common/builders/` directories from version 7.0 are deprecated in version 7.1 and scheduled for removal in version 8.0. Move module-specific builders to `<namespace>/builders/` and reference them by `plugin_id` in `manifest.yaml`.

In the next steps---[Data foundation module creation](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-foundation.md.txt#data-foundation-module-example)
and
[Data product module creation](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-product.md.txt#data-product-module-example)---you
learn how to add foundation and data product modules to a custom namespace.

## What's next

- Next step: [Data foundation module creation](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-foundation.md.txt)
- Back to [Overview](https://docs.cloud.google.com/cortex/docs/extensibility-guide.md.txt)