# Chalk Python SDK Reference: Features
source: https://docs.chalk.ai/api-docs#section-features

Features define the data that you want to compute and store. Your features are defined as Python classes that look like dataclasses. For example:

```python
from chalk.features import features, DataFrame, _
@features
class CreditCard:
   id: int
   user_id: "User.id"
   limit: float
@features
class User:
   id: int
   name: str
   email: str
   credit_cards: DataFrame[CreditCard]
   total_limit: float = _.credit_cards[_.limit].sum()
```

Features can be nested, as with `credit_cards` above. In this section, we'll dive into API components that make up the building blocks of features.

## `@features(owner, tags, etl_offline_to_online, max_staleness, online_store_config, cache_nulls, cache_defaults, part_of, name, description, singleton)`
source: https://docs.chalk.ai/api-docs#features

Chalk lets you spell out your features directly in Python.

Features are namespaced to a `FeatureSet`. To create a new `FeatureSet`, apply the [`@features`](https://docs.chalk.ai/api-docs#features) decorator to a Python class with typed attributes. A `FeatureSet` is constructed and functions much like Python's own [`dataclass`](https://docs.python.org/3/library/dataclasses.html).

**Parameters**

- `owner`: `str | None` = `None`
  The individual or team responsible for these features. The [Chalk Dashboard](https://chalk.ai/projects) will display this field, and alerts can be routed to owners.
- `tags`: `Tags | None` = `None`
  Added metadata for features for use in filtering, aggregations, and visualizations. For example, you can use tags to assign features to a team and find all features for a given team.
- `etl_offline_to_online`: `bool` = `False`
  When [`True`](https://docs.python.org/3/library/constants.html#True), Chalk copies this feature into the online environment when it is computed in offline resolvers. Setting `etl_offline_to_online` on a feature class assigns it to all features on the class which do not explicitly specify `etl_offline_to_online`.
- `max_staleness`: `Duration | None` = `None`
  When a feature is expensive or slow to compute, you may wish to cache its value. Chalk uses the terminology "maximum staleness" to describe how recently a feature value needs to have been computed to be returned without re-running a resolver. Assigning a `max_staleness` to the feature class assigns it to all features on the class which do not explicitly specify a `max_staleness` value of their own.
- `online_store_config`: `OnlineStoreConfig | None` = `None`
- `cache_nulls`: `CacheNullsType` = `True`
  When [`True`](https://docs.python.org/3/library/constants.html#True) (default), Chalk will cache all values, including nulls. When [`False`](https://docs.python.org/3/library/constants.html#False), Chalk will not update the null entry in the cache. When `"evict_nulls"`, Chalk will evict the entry that would have been null from the cache, if it exists.

  Concretely, suppose the current state of a database is `{a: 1, b: 2}`, and you write a row `{a: 2, b: None}`. Here is the expected result in the db:

  - `{a: 2, b: None}` when `cache_nulls=True` (default)
  - `{a: 2, b: 2}` when `cache_nulls=False`
  - `{a: 2}` when `cache_nulls="evict_nulls"`
- `cache_defaults`: `CacheDefaultsType` = `True`
  When [`True`](https://docs.python.org/3/library/constants.html#True) (default), Chalk will cache all values, including default values. When [`False`](https://docs.python.org/3/library/constants.html#False), Chalk will not update the default entry in the cache. When `"evict_defaults"`, Chalk will evict the entry that would have been a default value from the cache, if it exists.

  Concretely, suppose the current state of a database is `{a: 1, b: 2}`, and you write a row `{a: 2, b: "default"}`, and the default value for feature b is `"default"`. Here is the expected result in the db:

  - `{a: 2, b: "default"}` when `cache_defaults=True`
  - `{a: 2, b: 2}` when `cache_defaults=False`
  - `{a: 2}` when `cache_defaults="evict_defaults"`

  The `cache_nulls` and `cache_defaults` options can be used together on the same feature with the following exceptions: if `cache_nulls=False`, then `cache_defaults` cannot be `"evict_defaults"`, and if `cache_nulls="evict_defaults"`, then `cache_defaults` cannot be [`False`](https://docs.python.org/3/library/constants.html#False).
- `part_of`: `str | None` = `None`
  Use `part_of` to group features as part of an existing [`@features`](https://docs.chalk.ai/api-docs#features) class without adding every field to the same Python class definition. Chalk folds the auxiliary class's fields into the target feature class named by `part_of`, so the deployed feature FQNs use the target namespace. For example, defining `balance_amount` on `@features(part_of="User") class UserBalanceFeatures` creates `user.balance_amount`, not `user_balance_features.balance_amount`. Reference features in queries and resolver annotations from the target class, such as `User.balance_amount`; keep the primary key on the target class.

**Other parameters**

- `cls`: `Type[T] | None` = `None`
  The decorated class. You shouldn't need to pass this argument.
- `name`: `str | None` = `None`
  The name for the feature set. By default, the name of a feature is taken from the name of the attribute on the class, prefixed with the camel-cased name of the class.
- `description`: `str | None` = `None`
  The description of the entire feature set. This will be displayed in the [Chalk Dashboard](https://chalk.ai/projects) and can be helpful for documentation purposes. Takes precedence over the description in the class docstring if both are provided.
- `singleton`: `bool` = `False`
  If [`True`](https://docs.python.org/3/library/constants.html#True), the feature set is a singleton, and there will be only one instance of the class. Because there is only one instance, a singleton feature class does not have a primary key. Features defined on a singleton feature class are available in all resolvers, regardless of whatever other features are used as inputs to the resolver.

**Examples**

```python
from chalk.features import features
@features(
    owner="andy@chalk.ai",
    max_staleness="30m",
    etl_offline_to_online=True,
    tags="user-group",
)
class User:
    id: str
    # Comments here appear in the web!
    # :tags: pii
    name: str | None
    # :owner: userteam@mycompany.com
    location: LatLng
```

## `feature(owner, tags, version, default_version, max_staleness, cache_nulls, cache_defaults, etl_offline_to_online, min, max, min_length, max_length, strict, validations, dtype, default, underscore, expression, offline_expression, deprecated, store_online, store_offline, versions, typ, materialization, description, name, primary, encoder, decoder, offline_ttl)`
source: https://docs.chalk.ai/api-docs#feature

Add metadata and configuration to a feature.

**Parameters**

- `owner`: `str | None` = `None`
  You may also specify which person or group is responsible for a feature. The owner tag will be available in Chalk's web portal. Alerts that do not otherwise have an owner will be assigned to the owner of the monitored feature. Read more at [Owner](https://docs.chalk.ai/docs/feature-discovery#owner)

  ```python
  from chalk.features import features, feature
  from datetime import date
  @features
  class User:
      id: str
      # :owner: user-team@company.com
      name: str
      dob: date = feature(owner="user-team@company.com")
  ```
- `tags`: `Tags | None` = `None`
  Add metadata to a feature for use in filtering, aggregations, and visualizations. For example, you can use tags to assign features to a team and find all features for a given team. Read more at [Tags](https://docs.chalk.ai/docs/feature-discovery#tags)

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      # :tags: pii
      name: str
      dob: date = feature(tags=["pii"])
  ```
- `version`: `int | None` = `None`
  The maximum version for a feature. Versioned features can be referred to with the `@` operator:

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      score: int = feature(version=2)
  str(User.score @ 2)
  ```

  ```python
  "user.score@2"
  ```

  See more at [Versioning](https://docs.chalk.ai/docs/feature-versions)
- `default_version`: `int` = `1`
  The default version for a feature. When you reference a versioned feature without the `@` operator, you reference the `default_version`. Set to `1` by default.

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      score: int = feature(version=2, default_version=2)
  str(User.score)
  ```

  ```python
  "user.score"
  ```

  See more at [Default versions](https://docs.chalk.ai/docs/feature-versions#default-versions)
- `max_staleness`: `... | Duration | None` = `...`
  When a feature is expensive or slow to compute, you may wish to cache its value. Chalk uses the terminology "maximum staleness" to describe how recently a feature value needs to have been computed to be returned without re-running a resolver. Read more at [Feature Caching](https://docs.chalk.ai/docs/feature-caching)
- `cache_nulls`: `CacheNullsType | None` = `None`
  When [`True`](https://docs.python.org/3/library/constants.html#True) (default), Chalk will cache all values, including nulls.

  When [`False`](https://docs.python.org/3/library/constants.html#False), Chalk will not update the null entry in the cache.

  When `"evict_nulls"`, Chalk will evict the entry that would have been null from the cache, if it exists.

  Concretely, suppose the current state of a database is `{a: 1, b: 2}`, and you write a row `{a: 2, b: None}`. Here is the expected result in the db:

  - `{a: 2, b: None}` when `cache_nulls=True` (default)
  - `{a: 2, b: 2}` when `cache_nulls=False`
  - `{a: 2}` when `cache_nulls="evict_nulls"`
- `cache_defaults`: `CacheDefaultsType | None` = `None`
  When [`True`](https://docs.python.org/3/library/constants.html#True) (default), Chalk will cache all values, including default values.

  When [`False`](https://docs.python.org/3/library/constants.html#False), Chalk will not update the default entry in the cache.

  When `"evict_defaults"`, Chalk will evict the entry that would have been a default value from the cache, if it exists.

  Concretely, suppose the current state of a database is `{a: 1, b: 2}`, and you write a row `{a: 2, b: "default"}`, and the default value for feature b is `"default"`. Here is the expected result in the db:

  - `{a: 2, b: "default"}` when `cache_defaults=True`
  - `{a: 2, b: 2}` when `cache_defaults=False`
  - `{a: 2}` when `cache_defaults="evict_defaults"`

  The `cache_nulls` and `cache_defaults` options can be used together on the same feature with the following exceptions: if `cache_nulls=False`, then `cache_defaults` cannot be `"evict_defaults"`, and if `cache_nulls="evict_defaults"`, then `cache_defaults` cannot be [`False`](https://docs.python.org/3/library/constants.html#False).
- `etl_offline_to_online`: `bool | None` = `None`
  When [`True`](https://docs.python.org/3/library/constants.html#True), Chalk copies this feature into the online environment when it is computed in offline resolvers. Read more at [Reverse ETL](https://docs.chalk.ai/docs/reverse-etl)
- `min`: `_TRich | None` = `None`
  If specified, when this feature is computed, Chalk will check that `x >= min`.

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      fico_score: int = feature(min=300, max=850)
  ```
- `max`: `_TRich | None` = `None`
  If specified, when this feature is computed, Chalk will check that `x <= max`.

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      fico_score: int = feature(min=300, max=850)
  ```
- `min_length`: `int | None` = `None`
  If specified, when this feature is computed, Chalk will check that `len(x) >= min_length`.

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      name: str = feature(min_length=1)
  ```
- `max_length`: `int | None` = `None`
  If specified, when this feature is computed, Chalk will check that `len(x) <= max_length`.

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      name: str = feature(min_length=1000)
  ```
- `strict`: `bool` = `False`
  If [`True`](https://docs.python.org/3/library/constants.html#True), if this feature does not meet the validation criteria, Chalk will not persist the feature value and will treat it as failed.
- `validations`: `list[Validation] | None` = `None`
  A list of validations to apply to this feature. Generally, [`max`](https://docs.chalk.ai/api-docs#max), [`min`](https://docs.chalk.ai/api-docs#min), `max_length`, and `min_length` are more convenient, but the parameter `strict` applies to all of those parameters. Use this parameter if you want to mix strict and non-strict validations.
- `dtype`: `pa.DataType | None` = `None`
  The backing `pyarrow.DataType` for the feature. This parameter can be used to control the storage format of data. For example, if you have a lot of data that could be represented as smaller data types, you can use this parameter to save space.

  ```python
  import pyarrow as pa
  from chalk.features import features, feature
  @features
  class WatchEvent:
      id: str
      duration_hours: float = feature(dtype=pa.float8())
  ```
- `default`: `_TRich | ...` = `...`
  The default value of the feature if it otherwise can't be computed. If you don't need to specify other metadata, you can also assign a default in the same way you would assign a default to a [`dataclass`](https://docs.python.org/3/library/dataclasses.html):

  ```python
  from chalk.features import features
  @features
  class User:
      num_purchases: int = 0
  ```
- `underscore`: `Underscore | None` = `None`
- `expression`: `Underscore | None` = `None`
  An underscore expression for defining the feature. Typically, this value is assigned directly to the feature without needing to use the `feature(...)` function. However, if you want to define other properties, like a `default` or `max_staleness`, you'll want to use the `expression` keyword argument.

  ```python
  from chalk.features import features
  from chalk import _
  @features
  class Receipt:
      subtotal: int
      tax: int = 0  # Default value, without other metadata
      total: int = feature(expression=_.subtotal + _.tax, default=0)
  ```

  See more at [Expressions](https://docs.chalk.ai/docs/expression)
- `offline_expression`: `Underscore | None` = `None`
  Defines an alternate expression to compute the feature during offline queries.
- `deprecated`: `bool` = `False`
  If [`True`](https://docs.python.org/3/library/constants.html#True), this feature is considered deprecated, which impacts the dashboard, alerts, and warnings.

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      name: str = feature(deprecated=True)
  ```
- `store_online`: `bool` = `True`
  By default [`True`](https://docs.python.org/3/library/constants.html#True). Setting to [`False`](https://docs.python.org/3/library/constants.html#False) will prevent this feature from being written to the online store.
- `store_offline`: `bool` = `True`
  By default [`True`](https://docs.python.org/3/library/constants.html#True). Setting to [`False`](https://docs.python.org/3/library/constants.html#False) will prevent this feature from being written to the offline store.
- `versions`: `dict[int, _TRich] | None` = `None`
  A map from integer feature version to feature definition. If this argument is used, no other argument to [`features`](https://docs.chalk.ai/api-docs#features) can be used.

  ```python
  from chalk.features import features, feature
  @features
  class User:
      id: str
      score: int
      banned: bool = feature(versions={
          1: feature(
               deprecated=True,
               description="Prior thresholds we used",
               expression=_.score > 900,
          ),
          2: feature(
               description="New cutoff released by Monica's team",
               expression=_.score > 300 | (_.score < 100 & _.id == "admin"),
          ),
      })
  ```
- `typ`: `Type[_TRich] | None` = `None`
  The type of the feature—this can be used as an alternative to the annotation in notebook feature definitions.
- `materialization`: `True | None` = `None`

**Other parameters**

- `description`: `str | None` = `None`
  Descriptions are typically provided as comments preceding the feature definition. For example, you can document a `fraud_score` feature with information about the values as follows:

  ```python
  from chalk.features import features
  @features
  class User:
      # 0 to 100 score indicating an identity match.
      fraud_score: float
  ```

  You can also specify the description directly with this parameter. Read more at [Description](https://docs.chalk.ai/docs/feature-discovery#description)
- `name`: `str | None` = `None`
  The name for the feature. By default, the name of a feature is the name of the attribute on the class, prefixed with the camel-cased name of the class. Note that if you provide an explicit name, the namespace, determined by the feature class, will still be prepended. See [`features`](https://docs.chalk.ai/api-docs#features) for more details.
- `primary`: `bool | None` = `None`
  If [`True`](https://docs.python.org/3/library/constants.html#True), this feature is considered a primary key for the feature class. Note that a feature class cannot have more than one primary key.

  Typically, you will not need to use this parameter. Features named `id` are declared primary keys by default.

  If you have primary key feature with a name other than `id`, you can use this parameter, or the class [`Primary`](https://docs.chalk.ai/api-docs#Primary) to indicate the primary key. For example:

  ```python
  from chalk.features import features, Primary
  @features
  class User:
      uid: Primary[int]
  ```

  ```python
  from chalk.features import features, feature
  @features
  class User:
      uid: int = feature(primary=True)
  ```
- `encoder`: `TEncoder[_TPrim, _TRich] | None` = `None`
- `decoder`: `TDecoder[_TPrim, _TRich] | None` = `None`
- `offline_ttl`: `... | Duration | None` = `...`
  Sets a maximum age for values eligible to be retrieved from the offline store, defined in relation to the query's current point-in-time.

**Returns**

`_TRich`

The type of the input feature, given by `_TRich`.

**Examples**

```python
from chalk.features import Primary, features, feature
@features
class User:
    uid: Primary[int]
    # Uses a default value of 0 when one cannot be computed.
    num_purchases: int = 0
    # Description of the name feature.
    # :owner: fraud@company.com
    # :tags: fraud, credit
    name: str = feature(
        max_staleness="10m",
        etl_offline_to_online=True
    )
    score: int = feature(
        version=2, default_version=2
    )
```

## `has_one(f)`
source: https://docs.chalk.ai/api-docs#has_one

Specify a feature that represents a one-to-one relationship.

This function allows you to explicitly specify a join condition between two [`@features`](https://docs.chalk.ai/api-docs#features) classes. When there is only one way to join two classes, we recommend using the foreign-key definition instead of this [`has_one`](https://docs.chalk.ai/api-docs#has_one) function. For example, if you have a `User` class and a `Card` class, and each user has one card, you can define the `Card` and `User` classes as follows:

```python
from chalk.features import features
@features
class User:
    id: str
@features
class Card:
    id: str
    user_id: User.id
    user: User
```

However, if `User` has two cards (say, a primary and secondary), the foreign key syntax cannot be used to define the relationship, and you should use the [`has_one`](https://docs.chalk.ai/api-docs#has_one) function.

Read more at [Has One](https://docs.chalk.ai/docs/has-one)

**Parameters**

- `f`: `Callable[[], Any]`
  The join condition between [`@feature`](https://docs.chalk.ai/api-docs#feature) classes. This argument is callable to allow for forward references to members of this class and the joined class.

**Examples**

```python
from chalk.features import features, has_one
@features
class Card:
    id: str
    user_id: str
    balance: float
@features
class User:
    id: str
    card: Card = has_one(
        lambda: User.id == Card.user_id
    )
```

## `has_many(f, max_staleness, online_store_max_items)`
source: https://docs.chalk.ai/api-docs#has_many

Specify a feature that represents a one-to-many relationship.

**Parameters**

- `f`: `Callable[[], Any]`
  The join condition between [`@features`](https://docs.chalk.ai/api-docs#features) classes. This argument is callable to allow for forward references to members of this class and the joined class.
- `max_staleness`: `Duration | None | ...` = `...`
  The maximum staleness of the joined feature. The items in the joined feature aggregate, storing the latest values of the joined feature for each primary key in the joined feature.
- `online_store_max_items`: `int | None` = `None`
  The maximum number of items to cache for the joined feature. The items in the joined feature aggregate, storing the latest values of the joined feature for each primary key in the joined feature.

**Examples**

```python
from chalk.features import DataFrame, features, has_many
@features
class Card:
    id: str
    user_id: str
    balance: float
@features
class User:
    id: str
    cards: DataFrame[Card] = has_many(
        lambda: User.id == Card.user_id
    )
```

## `after(days_ago, hours_ago, minutes_ago, seconds_ago, index, weeks_ago, milliseconds_ago, microseconds_ago)`
source: https://docs.chalk.ai/api-docs#after

The function [`after`](https://docs.chalk.ai/api-docs#after) can be used with [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) to compute windowed features.

[`after`](https://docs.chalk.ai/api-docs#after) filters a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) relative to the current time in context, such that if the [`after`](https://docs.chalk.ai/api-docs#after) filter is defined as `now - {time_window}`, the filter will include all features with timestamps t where `now - {time_window} <= t <= now`. This time could be in the past if you’re using an offline resolver. Using window functions ensures that you maintain point-in-time correctness.

The parameters to [`after`](https://docs.chalk.ai/api-docs#after) take many keyword arguments describing the time relative to the present.

**Parameters**

- `days_ago`: `int` = `0`
  Number of days ago.
- `hours_ago`: `int` = `0`
  Number of hours ago.
- `minutes_ago`: `int` = `0`
  Number of minutes ago.
- `seconds_ago`: `int` = `0`
  Number of seconds ago.
- `index`: `Any` = `None`
  The feature to use for the filter. By default, `index` is the `FeatureTime` of the referenced feature class.

**Other parameters**

- `weeks_ago`: `int` = `0`
  Number of weeks ago.
- `milliseconds_ago`: `int` = `0`
  Number of milliseconds ago.
- `microseconds_ago`: `int` = `0`
  Number of microseconds ago.

**Returns**

`Any`

A filter for the [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame).

**Examples**

```python
from chalk.features import DataFrame, features
@features
class Card:
    ...
@features
class User:
    cards: DataFrame[Card]
User.cards[after(hours_ago=1, minutes_ago=30)]
```

## `before(days_ago, hours_ago, minutes_ago, seconds_ago, index, weeks_ago, milliseconds_ago, microseconds_ago)`
source: https://docs.chalk.ai/api-docs#before

The function [`before`](https://docs.chalk.ai/api-docs#before) can be used with [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) to compute windowed features.

[`before`](https://docs.chalk.ai/api-docs#before) filters a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) relative to the current time in context such that if the [`before`](https://docs.chalk.ai/api-docs#before) filter is defined as `now - {time_window}`, the filter will include all features with timestamps t where `t <= now - {time_window}`. This time could be in the past if you’re using an offline resolver. Using window functions ensures that you maintain point-in-time correctness.

The parameters to [`before`](https://docs.chalk.ai/api-docs#before) take many keyword arguments describing the time relative to the present.

**Parameters**

- `days_ago`: `int` = `0`
  Number of days ago.
- `hours_ago`: `int` = `0`
  Number of hours ago.
- `minutes_ago`: `int` = `0`
  Number of minutes ago.
- `seconds_ago`: `int` = `0`
  Number of seconds ago.
- `index`: `Any` = `None`
  The feature to use for the filter. By default, `index` is the `FeatureTime` of the referenced feature class.

**Other parameters**

- `weeks_ago`: `int` = `0`
  Number of weeks ago.
- `milliseconds_ago`: `int` = `0`
  Number of milliseconds ago.
- `microseconds_ago`: `int` = `0`
  Number of microseconds ago.

**Returns**

`Any`

A filter for a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame).

**Examples**

```python
from chalk.features import DataFrame, features
@features
class Card:
    ...
@features
class User:
    cards: DataFrame[Card]
User.cards[before(hours_ago=1, minutes_ago=30)]
```

## `Windowed`
source: https://docs.chalk.ai/api-docs#Windowed

Class (bases: `Generic[TRich]`)

Declare a windowed feature.

**Examples**

```python
@features
class User:
    failed_logins: Windowed[int] = windowed("10m", "24h")
```

**Attributes**

- `buckets_seconds`: `set[int]`
- `kind`: `Type[TRich]`

### `Windowed.__getitem__(item)`
source: https://docs.chalk.ai/api-docs#Windowed.__getitem__

## `windowed(buckets, days, hours, minutes, owner, tags, default, max_staleness, offline_ttl, version, etl_offline_to_online, min, max, min_length, max_length, strict, validations, expression, offline_expression, materialization, description, name, encoder, decoder, dtype, typ)`
source: https://docs.chalk.ai/api-docs#windowed

Create a windowed feature.

See more at [Windowed Aggregations](https://docs.chalk.ai/docs/aggregations)

**Parameters**

- `buckets`: `str` = `()`
  The size of the buckets for the window function. Buckets are specified as strings in the format `"1d"`, `"2h"`, `"1h30m"`, etc. You may also choose to specify the buckets using the days, hours, and minutes parameters instead. The buckets parameter is helpful if you want to use multiple units to express the bucket size, like `"1h30m"`.
- `days`: `Iterable[int]` = `()`
  Convenience parameter for specifying the buckets in days. Using this parameter is equvalent to specifying the buckets parameter with a string like `"1d"`.
- `hours`: `Iterable[int]` = `()`
  Convenience parameter for specifying the buckets in hours. Using this parameter is equvalent to specifying the buckets parameter with a string like `"1h"`.
- `minutes`: `Iterable[int]` = `()`
  Convenience parameter for specifying the buckets in minutes. Using this parameter is equvalent to specifying the buckets parameter with a string like `"1m"`.
- `owner`: `str | None` = `None`
  You may also specify which person or group is responsible for a feature. The owner tag will be available in Chalk's web portal. Alerts that do not otherwise have an owner will be assigned to the owner of the monitored feature.
- `tags`: `Any | None` = `None`
  Add metadata to a feature for use in filtering, aggregations, and visualizations. For example, you can use tags to assign features to a team and find all features for a given team.
- `default`: `TRich | ...` = `...`
  The default value of the feature if it otherwise can't be computed.
- `max_staleness`: `Duration | ... | None` = `...`
  When a feature is expensive or slow to compute, you may wish to cache its value. Chalk uses the terminology "maximum staleness" to describe how recently a feature value needs to have been computed to be returned without re-running a resolver.

  See more at [Feature Caching](https://docs.chalk.ai/docs/feature-caching)
- `offline_ttl`: `Duration | ... | None` = `...`
  Sets a maximum age for values eligible to be retrieved from the offline store, defined in relation to the query's current point-in-time.
- `version`: `int | None` = `None`
  Feature versions allow you to manage a feature as its definition changes over time.

  The [`version`](https://docs.chalk.ai/api-docs#version) keyword argument allows you to specify the maximum number of versions available for this feature.

  See more at [Versioning](https://docs.chalk.ai/docs/feature-versions)
- `etl_offline_to_online`: `bool | None` = `None`
  When [`True`](https://docs.python.org/3/library/constants.html#True), Chalk copies this feature into the online environment when it is computed in offline resolvers.

  See more at [Reverse ETL](https://docs.chalk.ai/docs/reverse-etl)
- `min`: `TRich | None` = `None`
  If specified, when this feature is computed, Chalk will check that `x >= min`.
- `max`: `TRich | None` = `None`
  If specified, when this feature is computed, Chalk will check that `x <= max`.
- `min_length`: `int | None` = `None`
  If specified, when this feature is computed, Chalk will check that `len(x) >= min_length`.
- `max_length`: `int | None` = `None`
  If specified, when this feature is computed, Chalk will check that `len(x) <= max_length`.
- `strict`: `bool` = `False`
  If [`True`](https://docs.python.org/3/library/constants.html#True), if this feature does not meet the validation criteria, Chalk will not persist the feature value and will treat it as failed.
- `validations`: `list[Validation] | None` = `None`
  A list of Validations to apply to this feature.

  See more at https://docs.chalk.ai/api-docs#Validation
- `expression`: `Underscore | None` = `None`
  The expression to compute the feature. This is an underscore expression, like `_.transactions[_.amount].sum()`.
- `offline_expression`: `Underscore | None` = `None`
  Defines an alternate expression to compute the feature during offline queries.
- `materialization`: `MaterializationWindowConfig | True | None` = `None`
  Configuration for aggregating data. Pass `bucket_duration` with a [Duration](https://docs.chalk.ai/api-docs#Duration) to configure the bucket size for aggregation. If [`True`](https://docs.python.org/3/library/constants.html#True), each of the windows will use a bucket duration equal to its window duration.

  See more at https://docs.chalk.ai/docs/materialized_aggregations

**Other parameters**

- `description`: `str | None` = `None`
  Descriptions are typically provided as comments preceding the feature definition. For example, you can document a `email_count` feature with information about the values as follows:

  ```python
  from chalk.features import features
  from chalk.streams import Windowed, windowed
  @features
  class User:
      # Count of emails sent
      email_count: Windowed[int] = windowed("10m", "30m")
  ```

  You can also specify the description directly with this parameter:

  ```python
  from chalk.features import features
  from chalk.streams import Windowed, windowed
  @features
  class User:
      email_count: Windowed[int] = windowed(
          "10m",
          "30m",
          description="Count of emails sent",
      )
  ```
- `name`: `str | None` = `None`
  The name for the feature. By default, the name of a feature is the name of the attribute on the class, prefixed with the camel-cased name of the class. Note that if you provide an explicit name, the namespace, determined by the feature class, will still be prepended. See [`features`](https://docs.chalk.ai/api-docs#features) for more details.
- `encoder`: `TEncoder[TPrim, TRich] | None` = `None`
- `decoder`: `TDecoder[TPrim, TRich] | None` = `None`
- `dtype`: `pa.DataType | None` = `None`
  The backing `pyarrow.DataType` for the feature. This parameter can be used to control the storage format of data. For example, if you have a lot of data that could be represented as smaller data types, you can use this parameter to save space.

  ```python
  import pyarrow as pa
  from chalk.features import features
  from chalk.streams import Windowed, windowed
  @features
  class User:
      id: str
      email_count: Windowed[int] = windowed(
          "10m", "30m",
          dtype=pa.int16(),
      )
  ```
- `typ`: `Type[Any] | None` = `None`
  The Python type of the windowed values. Usually inferred from the `Windowed[...]` class annotation; required when there is no class body to infer from, as with `add_features(...)`.

**Returns**

`Windowed[TRich]`

Metadata for the windowed feature, parameterized by `TPrim` (the primitive type of the feature) and `TRich` (the decoded type of the feature, if `decoder` is provided).

**Examples**

```python
from chalk.features import features
from chalk.streams import windowed, Windowed
@features
class User:
    id: int
    email_count: Windowed[int] = windowed(days=range(1, 30))
    logins: Windowed[int] = windowed("10m", "1d", "30d")
User.email_count["7d"]
```

## `MaterializationWindowConfig`
source: https://docs.chalk.ai/api-docs#MaterializationWindowConfig

Class (bases: `TypedDict`)

Configuration for window aggregates. At least one of `bucket_duration` and `bucket_durations` must be provided.

If both are provided, `bucket_duration` acts as a default for the window materialization, which may be overridden by `bucket_duration`.

**Attributes**

- `bucket_duration`: `Duration`
  The duration of each bucket in the window, using a `chalk.Duration` string, e.g. `"1m"`, `"1h"`, `"1d"`.

  To use different bucket durations for different window sizes, see `bucket_durations` below.
- `bucket_durations`: `Mapping[Duration, Sequence[Duration] | Duration]`
  A mapping from the desired bucket duration to the window size(s) that should use that bucket duration.

  If `bucket_duration` is also provided, any window durations not specified in this mapping will pick up the bucket duration from the `bucket_duration` parameter.

  This parameter is useful when you have some very large windows and some very small windows. For example, if you have a 365-day window and a 10-minute window, you wouldn't want to maintain 365 days of 10-minute buckets in the online store. However, using a 1-day bucket for the 10-minute window would also lead to significantly more events fitting into the window than you might want.

  In this case, you could specify:

  ```python
  count: Windowed[int] = windowed(
      "1d", "7d", "60d", "365d",
      materialization={
          # 1-day buckets as a default, for the 7d window
          "bucket_duration": "1d",
          "bucket_durations": {
              # 10-minute buckets for the 1d window
              "10m": "1d",
              # 5-day buckets for 60d and 365d windows
              "5d": ["60d", "365d"],
          },
      },
      expression=_.events.count(),
  )
  ```
- `bucket_start`: `datetime`
  The lower bound of the first bucket. All buckets will start at some multiple of the bucket duration after this time.
- `bucket_starts`: `Mapping[datetime, Sequence[Duration] | Duration]`
  Used to specify a different bucket start for each window duration. Same format as `bucket_durations`.
- `backfill_schedule`: `CronTab | None`
  The schedule on which to automatically backfill the aggregation. For example, `"* * * * *"` or `"1h"`.
- `backfill_resolver`: `str | Resolver | None`
  The resolver to backfill the aggregation from. Defaults to the resolver an offline query would run.
- `backfill_start_time`: `datetime | None`
  The time to start backfilling from. Defaults to the earliest data `backfill_resolver` returns.
- `backfill_lookback_duration`: `Duration | None`
  How far before the previous backfill to re-read, sized to the latest-arriving data in the window.
- `backfill_tags`: `list[list[str]] | None`
  Optional resolver tags to use when running the scheduled aggregate backfill. Each inner list produces a separate scheduled backfill job that resolves data using resolvers matching those tags. For example, `[["tag1"], ["tag2", "tag3"]]` would create two scheduled backfill jobs, one for resolvers tagged "tag1" and one for "tag2, tag3".
- `continuous_resolver`: `str | Resolver | None`
  The resolver to apply continuous updates with. Defaults to the resolver an online query would run.
- `continuous_buffer_duration`: `Duration | None`
  The minimum period of time for which to sample data directly via online query, rather than from the backfilled aggregations.
- `offline_continuous_buffer_duration`: `Duration | None`
  The continuous buffer to use for offline queries, in place of `continuous_buffer_duration`.

  Offline queries read the backfilled aggregations, whose trailing edge lags the online path, so the span that has to be recomputed from raw events is a different one. Set this to size that span independently of the online buffer.

  When unset, offline queries use `continuous_buffer_duration`. Online queries and aggregate backfills always use `continuous_buffer_duration` and ignore this.

  ```python
  count: Windowed[int] = windowed(
      "1d", "7d",
      materialization={
          "bucket_duration": "1d",
          "continuous_buffer_duration": "1h",
          "offline_continuous_buffer_duration": "2d",
      },
      expression=_.events.count(),
  )
  ```
- `cache_aggregated_values`: `bool`
  If True, caches the computed, aggregated values for the given time windows in the online store. At query time the cached values are read instead of computed the aggregation from the buckets. This can be useful, for example, if one wants to store the materialized buckets in the offline store but only store the computed values in the online store to save space. The computed values in the online store will have the max-staleness specified by the windowed feature.

  In the example below, queries for `user.count["1d"]` will load the daily count from the online store as a single value, and fall back to computing it from hourly buckets if it's not cached.

  ` @features class User: ... count: Windowed[float] = windowed( materialization={ "bucket_durations": {"1d": "1h", "7d": "1d"}, "cache_aggregated_values": True }, expression=_.events.count(), max_staleness="30d", ) `
- `cached_values_only`: `bool`
  Only meaningful alongside `cache_aggregated_values`. If True, online queries serve the feature exclusively from its cached value: a cache miss returns the feature's default instead of falling back to reading and merging the aggregation buckets. Offline queries and aggregate backfills are unaffected, so the buckets are still maintained and still queryable offline.

  Use this when the online store holds only the computed values -- for example when the buckets live in the offline store, or when they are large enough that a fallback merge would blow the query's latency budget -- and a default is a better answer than a slow one.

  ` @features class User: ... count: Windowed[float] = windowed( materialization={ "bucket_durations": {"1d": "1h", "7d": "1d"}, "cache_aggregated_values": True, "cached_values_only": True, }, expression=_.events.count(), max_staleness="30d", ) `
- `allow_filter_migration`: `bool`
  If True, changes to the filter definitions will not invalidate existing materialized values in the online store.

## `Primary`
source: https://docs.chalk.ai/api-docs#Primary

Class

Marks a feature as the primary feature for a feature class.

Features named `id` on feature classes without an explicit primary feature are declared primary keys by default, and don't need to be marked with [`Primary`](https://docs.chalk.ai/api-docs#Primary).

If you have primary key feature with a name other than `id`, you can use this marker to indicate the primary key.

**Examples**

```python
from chalk.features import features
from chalk import Primary
@features
class User:
    username: Primary[str]
```

### `Primary.__class_getitem__(item)`
source: https://docs.chalk.ai/api-docs#Primary.__class_getitem__

**Parameters**

- `item`: `Type | str | int`
  The type of the feature value.

**Returns**

The type, with a special annotation indicating that it is a primary key.

**Examples**

```python
from chalk.features import features
from chalk import Primary
@features
class User:
    username: Primary[str]
```

## `Validation`
source: https://docs.chalk.ai/api-docs#Validation

Class (bases: `Generic[T]`)

Specify explicit data validation for a feature.

The [`feature()`](https://docs.chalk.ai/api-docs#feature) function can also specify these validations, but this class allows you to specify both strict and non-strict validations at the same time.

### `Validation.__init__(min, max, min_length, max_length, strict)`
source: https://docs.chalk.ai/api-docs#Validation.__init__

Set validation parameters for a feature.

**Parameters**

- `min`: `T | None` = `None`
  If specified, when this feature is computed, Chalk will check that `x >= min`.
- `max`: `T | None` = `None`
  If specified, when this feature is computed, Chalk will check that `x <= max`.
- `min_length`: `int | None` = `None`
  If specified, when this feature is computed, Chalk will check that `len(x) >= min_length`.
- `max_length`: `int | None` = `None`
  If specified, when this feature is computed, Chalk will check that `len(x) <= max_length`.
- `strict`: `bool` = `False`
  If [`True`](https://docs.python.org/3/library/constants.html#True), if this feature does not meet the validation criteria, Chalk will not persist the feature value and will treat it as failed.

**Examples**

```python
from chalk.features import features, feature
@features
class User:
    fico_score: int = feature(
        validations=[
            Validation(min=300, max=850, strict=True),
            Validation(min=300, max=320, strict=False),
            Validation(min=840, max=850, strict=False),
        ]
    )
    # If only one set of validations were needed,
    # you can use the [`feature`](#feature) function instead:
    first_name: str = feature(
        min_length=2, max_length=64, strict=True
    )
```

## `Vector`
source: https://docs.chalk.ai/api-docs#Vector

Class

The Vector class can be used type annotation to denote a Vector feature.

Instances of this class will be provided when working with raw vectors inside of resolvers. Generally, you do not need to construct instances of this class directly, as Chalk will automatically convert list-like features into [`Vector`](https://docs.chalk.ai/api-docs#Vector) instances when working with a [`Vector`](https://docs.chalk.ai/api-docs#Vector) annotation.

**Parameters**

data: numpy.Array | list[float] | pyarrow.FixedSizeListScalar The vector values

**Examples**

```python
from chalk.features import Vector, features
@features
class Document:
    embedding: Vector[1536]
```

**Attributes**

- `precision`: `'fp16' | 'fp32' | 'fp64'`
  The precision of the Vector

### `Vector.to_arrow_scalar()`
source: https://docs.chalk.ai/api-docs#Vector.to_arrow_scalar

Convert a vector to a PyArrow array.

**Returns**

`pa.FixedSizeListScalar`

The vector, as a PyArrow array.

### `Vector.to_arrow_array()`
source: https://docs.chalk.ai/api-docs#Vector.to_arrow_array

Convert a vector to a PyArrow array.

**Returns**

`pa.Array`

The vector, as a PyArrow array.

### `Vector.to_numpy(writable)`
source: https://docs.chalk.ai/api-docs#Vector.to_numpy

Convert the vector to a Numpy array.

**Parameters**

- `writable`: `bool` = `False`
  Whether the numpy array should be writable. If so, an extra copy of the vector data will be made.

**Returns**

`np.ndarray`

The vector, as a numpy array.

### `Vector.to_pylist()`
source: https://docs.chalk.ai/api-docs#Vector.to_pylist

Convert the vector to a Python list.

**Returns**

`list[float]`

The vector, as a list of Python floats

### `Vector.__class_getitem__(item)`
source: https://docs.chalk.ai/api-docs#Vector.__class_getitem__

**Overloads**

##### `Vector.__class_getitem__(item)`

Create a Vector type with the specified precision and number of dimensions.

**Parameters**

- `item`: `tuple['fp32' | 'fp64' | 'fp16', int]`
  The first element is the precision, and the second element is the number of dimensions.

**Returns**

`Type[Vector]`

A vector type

##### `Vector.__class_getitem__(item)`

Create a Vector type of with float-16 precision and the specified number of dimensions. This helper is equivalent to `Vector['fp16', N]`.

**Parameters**

- `item`: `int`
  The number of dimensions.

**Returns**

`Type[Vector]`

A vector type

### `Vector.is_near(other, metric)`
source: https://docs.chalk.ai/api-docs#Vector.is_near

Define a nearest neighbor relationship for performing Vector similarity search.metric: "l2" | "ip" | "cos" The metric to use to compute distance between two vectors. L2 Norm ("l2"), Inner Product ("ip"), and Cosine ("cos") are supported. Defaults to "l2".

**Parameters**

- `other`: `Any`
  The other vector feature. This vector must have the same dtype and dimensions.
- `metric`: `'l2' | 'ip' | 'cos'` = `'l2'`

**Returns**

`Filter`

A nearest neighbor relationship filter.
