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

## `@online(environment, tags, cron, owner, timeout, resource_hint, static, accelerate_python, incremental, fn, machine_type, name, total, unique_on, partitioned_by, resource_group, output_row_order, max_batch_size, venv, handle_duplicate_outputs)`
source: https://docs.chalk.ai/api-docs#online

Decorator to create an online resolver.

**Parameters**

- `environment`: `Environments | None` = `None`
  Environments are used to trigger behavior in different deployments such as staging, production, and local development. For example, you may wish to interact with a vendor via an API call in the production environment, and opt to return a constant value in a staging environment.

  Environment can take one of three types:

  - [`None`](https://docs.python.org/3/library/constants.html#None) (default) - candidate to run in every environment
  - [`str`](https://docs.python.org/3/library/stdtypes.html#str) - run only in this environment
  - `list[str]` - run in any of the specified environment and no others

  Read more at [Environments](https://docs.chalk.ai/docs/resolver-environments)
- `tags`: `Tags | None` = `None`
  Allow you to scope requests within an environment. Both tags and environment need to match for a resolver to be a candidate to execute.

  You might consider using tags, for example, to change out whether you want to use a sandbox environment for a vendor, or to bypass the vendor and return constant values in a staging environment.

  Read more at [Routing tags](https://docs.chalk.ai/docs/resolver-tags)
- `cron`: `CronTab | Duration | Cron | None` = `None`
  You can schedule resolvers to run on a pre-determined schedule via the cron argument to resolver decorators.

  Cron can sample all examples, a subset of all examples, or a custom provided set of examples.

  Read more at [Scheduling](https://docs.chalk.ai/docs/resolver-cron)
- `owner`: `str | None` = `None`
  Individual or team responsible for this resolver. The [Chalk Dashboard](https://chalk.ai/projects) will display this field, and alerts can be routed to owners.
- `timeout`: `Duration | None` = `None`
  You can specify the maximum [`Duration`](https://docs.chalk.ai/api-docs#Duration) to wait for the resolver's result. Once the resolver's runtime exceeds the specified duration, a timeout error will be returned along with each output feature.

  Read more at [Timeout](https://docs.chalk.ai/docs/timeout).
- `resource_hint`: `ResourceHint | None` = `None`
  Whether this resolver is bound by CPU, I/O, or GPU. Chalk uses the resource hint to optimize resolver execution.
- `static`: `bool` = `False`
  Whether this resolver should be invoked once during planning time to build a static computation graph. If [`True`](https://docs.python.org/3/library/constants.html#True), all inputs will either be `StaticOperators` (for has-many and [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) relationships) or `StaticExpressions` (for individual features). The resolver must return a [`StaticOperator`](https://docs.chalk.ai/api-docs#StaticOperator) as output.
- `accelerate_python`: `'require' | 'auto' | 'never' | None` = `None`
  You can specify that a resolver _must_ be statically accelerated to not run in python with `accelerate_python="require"`, specify that a resolver _must_ be run in python with `accelerate_python="never"`, or use the default behavior `accelerate_python="auto"`, where resolvers will be accelerated if able, else they will run in python.
- `incremental`: `IncrementalConfig | None` = `None`

**Other parameters**

- `fn`: `Callable[P, T] | None` = `None`
  The function that you're decorating as a resolver.
- `machine_type`: `MachineType | None` = `None`
  You can optionally specify that resolvers need to run on a machine other than the default. Must be configured in your deployment.
- `name`: `str | None` = `None`
  An alternative short name for the resolver, to use instead of the function name.
- `total`: `bool` = `False`
  Whether this resolver returns all ids of a given namespace. To have this annotation, the resolver must take no arguments and return a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame). Typically, this annotation would be used in a SQL-file resolver.
- `unique_on`: `Collection[Any] | None` = `None`
  A list of features that must be unique for each row of the output. This enables unique optimizations in the resolver execution. Only applicable to resolvers that return a DataFrame.
- `partitioned_by`: `Collection[Any] | None` = `None`
  A list of features that correspond to partition keys in the data source. This field indicates that this resolver executes its query against a data storage system that is partitioned by a particular set of columns. This is most common with data-warehouse sources like Snowflake, BigQuery or Databricks.
- `resource_group`: `str | None` = `None`
  The resource group for the resolver: this is used to isolate execution of the resolver onto a separate pod (or set of nodes), allowing model inference to be run in a separate environment, such as on a GPU-enabled node.
- `output_row_order`: `'one-to-one' | None` = `None`
  If set to "one-to-one", signals the planner that this resolver is logically equivalent to a batched scalar resolver. A resolver marked `output_row_order="one-to-one"` must adhere to the following constraints:

  - the resolver must take in one dataframe input and return a dataframe output
  - both the input and the output must have the pkey column
  - the operation must be logically one-to-one - ie all corresponding input rows have a corresponding output row
  - the order of the rows must be preserved

  Here is an example resolver that can be marked one-to-one to batch the account_ids lookup

  ```python
  @online(output_row_order="one-to-one")
  def my_one_to_one_df_resolver(
      input: DataFrame[User.id, User.account_info]
  ) -> DataFrame[User.id, User.account_ids]:
      input_as_pydict = input.to_pyarrow().to_pydict()
      info_to_ids_map = get_batch_info_to_ids_map(input_as_pydict)
      return DataFrame({
          User.id: input_as_pydict[str(User.id)],
          User.account_info: [
              info_to_ids_map.get(info, []) for info in input_as_pydict[str(User.account_info)]
          ]
      })
  ```
- `max_batch_size`: `int | None` = `None`
  Only valid for DataFrame -> DataFrame resolvers that declare `Index` in exactly one input DataFrame and in the output DataFrame. The engine slices the input and invokes the resolver once per chunk of at most this many rows, streaming outputs incrementally. [`None`](https://docs.python.org/3/library/constants.html#None) (the default) means unlimited: a single invocation over all rows. The resolver `timeout` applies to each chunk invocation, and a chunk that raises produces an error for that chunk while the remaining chunks still emit data.

  ```python
  @online(max_batch_size=1024)
  def batch_embed(
      docs: DataFrame[Document.id, Document.text, Index]
  ) -> DataFrame[Document.id, Document.embedding, Index]:
      ...
  ```
- `venv`: `str | None` = `None`
  A virtual environment to use for the resolver. This is used to isolate the resolver from the default requirements, allowing different versions of packages to be used.
- `handle_duplicate_outputs`: `str | None` = `None`
  Controls how this resolver handles duplicate primary-key rows in its output. Only applicable to resolvers that return a DataFrame. Overrides the server-wide `DEFAULT_HANDLE_DUPLICATE_OUTPUTS` setting for this resolver only.

  Accepted values:

  - `"skip_validation"` — do not check for duplicates.
  - `"dedup_any"` — deduplicate by selecting one row and dropping all others silently.
  - `"error"` — raise an error if any primary-key value appears more than once.

  If [`None`](https://docs.python.org/3/library/constants.html#None) (the default), the server-wide default is used.

**Returns**

A [`ResolverProtocol`](https://docs.chalk.ai/api-docs#ResolverProtocol) which can be called as a normal function! You can unit-test resolvers as you would unit-test any other code.

Read more at [Unit Tests](https://docs.chalk.ai/docs/unit-tests)

**Examples**

```python
@online
def name_match(
    name: User.full_name,
    account_name: User.bank_account.title
) -> User.account_name_match_score:
    if name.lower() == account_name.lower():
        return 1.
    return 0.
```

## `@offline(environment, tags, cron, owner, timeout, resource_hint, static, accelerate_python, total, incremental, fn, machine_type, name, unique_on, partitioned_by, output_row_order, max_batch_size, venv, handle_duplicate_outputs)`
source: https://docs.chalk.ai/api-docs#offline

Decorator to create an offline resolver.

**Parameters**

- `environment`: `Environments | None` = `None`
  Environments are used to trigger behavior in different deployments such as staging, production, and local development. For example, you may wish to interact with a vendor via an API call in the production environment, and opt to return a constant value in a staging environment.

  Environment can take one of three types:

  - [`None`](https://docs.python.org/3/library/constants.html#None) (default) - candidate to run in every environment
  - [`str`](https://docs.python.org/3/library/stdtypes.html#str) - run only in this environment
  - `list[str]` - run in any of the specified environment and no others

  Read more at [Environments](https://docs.chalk.ai/docs/resolver-environments)
- `tags`: `Tags | None` = `None`
  Allow you to scope requests within an environment. Both tags and environment need to match for a resolver to be a candidate to execute.

  You might consider using tags, for example, to change out whether you want to use a sandbox environment for a vendor, or to bypass the vendor and return constant values in a staging environment.

  Read more at [Routing tags](https://docs.chalk.ai/docs/resolver-tags)
- `cron`: `CronTab | Duration | Cron | None` = `None`
  You can schedule resolvers to run on a pre-determined schedule via the cron argument to resolver decorators.

  Cron can sample all examples, a subset of all examples, or a custom provided set of examples.

  Read more at [Scheduling](https://docs.chalk.ai/docs/resolver-cron)
- `owner`: `str | None` = `None`
  Allows you to specify an individual or team who is responsible for this resolver. The [Chalk Dashboard](https://chalk.ai/projects) will display this field, and alerts can be routed to owners.
- `timeout`: `Duration | None` = `None`
  You can specify the maximum [`Duration`](https://docs.chalk.ai/api-docs#Duration) to wait for the resolver's result. Once the resolver's runtime exceeds the specified duration, a timeout error will be raised.

  Read more at [Timeout](https://docs.chalk.ai/docs/timeout).
- `resource_hint`: `ResourceHint | None` = `None`
  Whether this resolver is bound by CPU or I/O. Chalk uses the resource hint to optimize resolver execution.
- `static`: `bool` = `False`
  Whether this resolver should be invoked once during planning time to build a static computation graph. If [`True`](https://docs.python.org/3/library/constants.html#True), all inputs will either be `StaticOperators` (for has-many and dataframe relationships) or `StaticExpressions` (for individual features). The resolver must return a [`StaticOperator`](https://docs.chalk.ai/api-docs#StaticOperator) as output.
- `accelerate_python`: `'require' | 'auto' | 'never' | None` = `None`
  You can specify that a resolver _must_ be statically accelerated to not run in python with `accelerate_python="require"`, specify that a resolver _must_ be run in python with `accelerate_python="never"`, or use the default behavior `accelerate_python="auto"`, where resolvers will be accelerated if able, else they will run in python.
- `total`: `bool` = `False`
  Whether this resolver returns all ids of a given namespace. To have this annotation, the resolver must take no arguments and return a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame). Typically, this annotation would be used in a SQL-file resolver.
- `incremental`: `IncrementalConfig | None` = `None`

**Other parameters**

- `fn`: `Callable[P, T] | None` = `None`
  The function that you're decorating as a resolver.
- `machine_type`: `MachineType | None` = `None`
  You can optionally specify that resolvers need to run on a machine other than the default. Must be configured in your deployment.
- `name`: `str | None` = `None`
  An alternative short name for the resolver, to use instead of the function name.
- `unique_on`: `Collection[Any] | None` = `None`
  A list of features that must be unique for each row of the output. This enables unique optimizations in the resolver execution. Only applicable to resolvers that return a DataFrame.
- `partitioned_by`: `Collection[Any] | None` = `None`
  A list of features that correspond to partition keys in the data source. This field indicates that this resolver executes its query against a data storage system that is partitioned by a particular set of columns. This is most common with data-warehouse sources like Snowflake, BigQuery or Databricks.
- `output_row_order`: `'one-to-one' | None` = `None`
  If set to "one-to-one", signals the planner that this resolver is logically equivalent to a batched scalar resolver. A resolver marked `output_row_order="one-to-one"` must adhere to the following constraints:

  - the resolver must take in one dataframe input and return a dataframe output
  - both the input and the output must have the pkey column
  - the operation must be logically one-to-one - ie all corresponding input rows have a corresponding output row
  - the order of the rows must be preserved

  Here is an example resolver that can be marked one-to-one to batch the account_ids lookup

  ```python
  @offline(output_row_order="one-to-one")
  def my_one_to_one_df_resolver(
      input: DataFrame[User.id, User.account_info]
  ) -> DataFrame[User.id, User.account_ids]:
      input_as_pydict = input.to_pyarrow().to_pydict()
      info_to_ids_map = get_batch_info_to_ids_map(input_as_pydict)
      return DataFrame({
          User.id: input_as_pydict[str(User.id)],
          User.account_info: [
              info_to_ids_map.get(info, []) for info in input_as_pydict[str(User.account_info)]
          ]
      })
  ```
- `max_batch_size`: `int | None` = `None`
  Only valid for DataFrame -> DataFrame resolvers that declare `Index` in exactly one input DataFrame and in the output DataFrame. The engine slices the input and invokes the resolver once per chunk of at most this many rows, streaming outputs incrementally. [`None`](https://docs.python.org/3/library/constants.html#None) (the default) means unlimited: a single invocation over all rows. The resolver `timeout` applies to each chunk invocation, and a chunk that raises produces an error for that chunk while the remaining chunks still emit data.

  ```python
  @offline(max_batch_size=1024)
  def batch_embed(
      docs: DataFrame[Document.id, Document.text, Index]
  ) -> DataFrame[Document.id, Document.embedding, Index]:
      ...
  ```
- `venv`: `str | None` = `None`
  A virtual environment to use for the resolver. This is used to isolate the resolver from the default requirements, allowing different versions of packages to be used.
- `handle_duplicate_outputs`: `str | None` = `None`
  Controls how this resolver handles duplicate primary-key rows in its output. Only applicable to resolvers that return a DataFrame. Overrides the server-wide `DEFAULT_HANDLE_DUPLICATE_OUTPUTS` setting for this resolver only.

  Accepted values:

  - `"skip_validation"` — do not check for duplicates.
  - `"dedup_any"` — deduplicate by selecting one row and dropping all others silently.
  - `"error"` — raise an error if any primary-key value appears more than once.

  If [`None`](https://docs.python.org/3/library/constants.html#None) (the default), the server-wide default is used.

**Returns**

A [`ResolverProtocol`](https://docs.chalk.ai/api-docs#ResolverProtocol) which can be called as a normal function! You can unit-test resolvers as you would unit-test any other code.

Read more at [Unit Tests](https://docs.chalk.ai/docs/unit-tests)

**Examples**

```python
@offline(cron="1h")
def get_fraud_score(
    email: User.email,
    name: User.name,
) -> User.fraud_score:
    return socure.get_sigma_score(email, name)
```

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

Class

Detailed options for specify the schedule and filtering functions for Chalk batch jobs.

### `Cron.__init__(schedule, filter, sample)`
source: https://docs.chalk.ai/api-docs#Cron.__init__

Run an online or offline resolver on a schedule.

This class lets you add a filter or sample function to your cron schedule for a resolver. See the overloaded signatures for more information.

**Parameters**

- `schedule`: `CronTab | Duration`
  The period of the cron job. Can be either a crontab (`"0 * * * *"`) or a [`Duration`](https://docs.chalk.ai/api-docs#Duration) (`"2h"`).
- `filter`: `Callable[..., bool] | None` = `None`
  Optionally, a function to filter down the arguments to consider.

  See [Filtering examples](https://docs.chalk.ai/docs/resolver-cron#filtering-examples) for more information.
- `sample`: `Callable[[], DataFrame] | None` = `None`
  Explicitly provide the sample function for the cron job.

  See [Custom examples](https://docs.chalk.ai/docs/resolver-cron#custom-examples) for more information.

**Examples**

Using a filter

```python
def only_active_filter(v: User.active):
    return v
@online(cron=Cron(schedule="1d", filter=only_active_filter))
def score_user(d: User.signup_date) -> User.score:
    return ...
```

Using a sample function

```python
def s() -> DataFrame[User.id]:
    return DataFrame.read_csv(...)
@offline(cron=Cron(schedule="1d", sample=s))
def fn(balance: User.account.balance) -> ...:
```

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

Class (bases: `Protocol[P, T_co]`)

A resolver, returned from the decorators [`@offline`](https://docs.chalk.ai/api-docs#offline) and [`@online`](https://docs.chalk.ai/api-docs#online).

**Attributes**

- `function_definition`: `str | None`
  The content of the resolver as a string.
- `function_captured_globals`: `Mapping[str, FunctionCapturedGlobal] | None`
  A subset of the global variables mentioned inside of the function, which are saved here in order to allow the function to be emulated symbolically.
- `owner`: `str | None`
  Individual or team responsible for this resolver. The [Chalk Dashboard](https://chalk.ai/projects) will display this field, and alerts can be routed to owners.
- `environment`: `tuple[str, ...] | None`
  Environments are used to trigger behavior in different deployments such as staging, production, and local development. For example, you may wish to interact with a vendor via an API call in the production environment, and opt to return a constant value in a staging environment.

  ```
  Environment can take one of three types:
  - [`None`](https://docs.python.org/3/library/constants.html#None) (default) - candidate to run in every environment
  - [`str`](https://docs.python.org/3/library/stdtypes.html#str) - run only in this environment
  - `list[str]` - run in any of the specified environment and no others
  ```

  Read more at [Environments](https://docs.chalk.ai/docs/resolver-environments)
- `tags`: `tuple[str, ...] | None`
  Allow you to scope requests within an environment. Both tags and environment need to match for a resolver to be a candidate to execute.

  You might consider using tags, for example, to change out whether you want to use a sandbox environment for a vendor, or to bypass the vendor and return constant values in a staging environment.

  Read more at [Routing tags](https://docs.chalk.ai/docs/resolver-tags)
- `__doc__`: `str | None`
  The docstring of the resolver.
- `__name__`: `str`
  The function name of the resolver.
- `__module__`: `str`
  The python module where the function is defined
- `__annotations__`: `dict[str, Any]`
  The type annotations for the resolver
- `filename`: `str`
  The filename in which the resolver is defined.
- `name`: `str`
  The name of the resolver, either given by the name of the function, or by the keyword argument `name` given to [`@offline`](https://docs.chalk.ai/api-docs#offline) or [`@online`](https://docs.chalk.ai/api-docs#online).
- `resource_hint`: `ResourceHint | None`
  Whether this resolver is bound by CPU or I/O
- `static`: `bool`
  whether the resolver is static. Static resolvers are "executed" once during planning time to produce a computation graph.
- `accelerate_python`: `'require' | 'auto' | 'never' | None`
  whether to require that this resolver run/not run in python
- `runtime_contract`: `str | None`
  Opt-in runtime contract label. Set to `"strict"` by the [`@resolver`](https://docs.chalk.ai/api-docs#resolver) decorator and read by downstream planner/runtime code to enforce stricter validation than legacy [`@online`](https://docs.chalk.ai/api-docs#online) / [`@offline`](https://docs.chalk.ai/api-docs#offline) resolvers. [`None`](https://docs.python.org/3/library/constants.html#None) for resolvers declared with the legacy decorators.
- `max_batch_size`: `int | None`
  Max rows per invocation for DataFrame -> DataFrame resolvers that declare `Index` in their input and output DataFrames. The engine slices the input and invokes the resolver once per chunk of at most this many rows. [`None`](https://docs.python.org/3/library/constants.html#None) (the default) means unlimited: a single invocation over all rows.
- `fqn`: `str`
  The fully qualified name for the resolver

### `ResolverProtocol.__call__(args, kwargs)`
source: https://docs.chalk.ai/api-docs#ResolverProtocol.__call__

Returns the result of calling the function decorated with [`@offline`](https://docs.chalk.ai/api-docs#offline) or [`@online`](https://docs.chalk.ai/api-docs#online) with the given arguments.

**Parameters**

- `args`: `P.args` = `()`
  The arguments to pass to the decorated function. If one of the arguments is a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) with a filter or projection applied, the resolver will only be called with the filtered or projected data. Read more at https://docs.chalk.ai/docs/unit-tests#data-frame-inputs
- `kwargs`: `P.kwargs` = `{}`

**Returns**

`T_co`

The result of calling the decorated function with `args`. Useful for unit-testing.

Read more at [Unit Tests](https://docs.chalk.ai/docs/unit-tests)

**Examples**

```python
@online
def get_num_bedrooms(
    rooms: Home.rooms[Room.name == 'bedroom']
) -> Home.num_bedrooms:
    return len(rooms)
rooms = [
    Room(id=1, name="bedroom"),
    Room(id=2, name="kitchen"),
    Room(id=3, name="bedroom"),
]
assert get_num_bedrooms(rooms) == 2
```

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

Class

An immutable context that can be accessed from Python resolvers. This context wraps a JSON-compatible dictionary or JSON string with type restrictions.

**Examples**

```python
from chalk.client import ChalkClient
from chalk.features import features
from chalk import ChalkContext, online
import requests
import json
@features
class User:
    id: int
    endpoint_url: str
    endpoint_response: str
@online
def get_user_endpoint_response(endpoint_url: User.endpoint_url) -> User.endpoint_response:
    context_headers = {}
    optional_correlation_id = ChalkContext.get("request_correlation_id")
    if optional_correlation_id is not None:
        context_headers["correlation-id"] = optional_correlation_id
    response = requests.get(endpoint_url, headers=context_headers)
    return json.dumps(response.json())
ChalkClient().query(
    input={User.id: 1, User.endpoint_url: "https://api.example.com/message"},
    output=[User.endpoint_response],
    query_context={"request_correlation_id": "df0cc84b-bb0e-41b1-82cd-74ccd968b2fa"},
)
```

### `ChalkContext.get(key, default)`
source: https://docs.chalk.ai/api-docs#ChalkContext.get

**Parameters**

- `key`: `str`
  The key to get from the context.
- `default`: `JsonValue | None` = `None`
  The default value to return if the key is not found. None by default.

**Returns**

`JsonValue | None`

The value associated with the key in the context, or the default value if the key is not found.

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

Type alias: `str`

The type of machine to use.

You can optionally specify that resolvers need to run on a machine other than the default. Must be configured in your deployment.
