---
url: /dev/getting-started/troubleshooting.md
description: >-
  What scikit-link's errors and warnings mean and how to fix them: duplicate
  keys, orphan rows, unknown keys, detached models, missing time columns.
---

# Common errors and how to fix them

**Most scikit-link errors name the table, column or parameter at fault and,
when there is one, the fix. A few come from scikit-learn's own checks, such
as a missing cutoff column at prediction time. This page shows the messages you are most likely
to meet, what causes each one and what to change.** The errors derive from
`sklink.exceptions.SklinkError` and, like scikit-learn's, from the matching
built-in error, such as `ValueError`.

The examples below share two small tables.

```python
import pandas as pd
from sklink import Database

customers = pd.DataFrame({"customer_id": [1, 2, 3]})
orders = pd.DataFrame(
    {"order_id": [10, 11, 12], "customer_id": [1, 1, 2], "amount": [5.0, 7.5, 3.0]}
)
keys = {"customers": "customer_id", "orders": "order_id"}
links = [("orders.customer_id", "customers.customer_id")]


def show(error):
    print(f"{type(error).__name__}: {error}")
```

## Building the database

### Duplicate primary keys

```python
from sklink.exceptions import IntegrityError

twice = pd.concat([customers, customers.head(1)])
try:
    Database(
        tables={"customers": twice, "orders": orders},
        primary_keys=keys,
        relationships=links,
    )
except IntegrityError as error:
    show(error)
```

```text
IntegrityError: Primary key ['customer_id'] of table 'customers' has 1 duplicated values.
```

A primary key identifies one row. Remove the duplicates, or declare the
columns that together identify a row as a composite key, such as
`["store", "day"]`. See [describe your database](../tutorials/describe-your-database#composite-keys-and-several-links-to-the-same-table).

### Orders without a customer

```python
lost = pd.concat(
    [orders, pd.DataFrame({"order_id": [13], "customer_id": [99], "amount": [1.0]})]
)
try:
    Database(
        tables={"customers": customers, "orders": lost},
        primary_keys=keys,
        relationships=links,
    )
except IntegrityError as error:
    show(error)
```

```text
IntegrityError: Relationship 'orders.customer_id->customers' has 1 rows in 'orders' whose key has no matching row in 'customers'. Pass orphans='ignore' to keep them.
```

These are **orphan** rows. Exports often have a few. Pass `orphans="warn"` or
`orphans="ignore"` to `Database(...)` to keep them; no sample ever reaches
them.

### A column or table name that does not exist

```python
from sklink.exceptions import SchemaError

try:
    Database(
        tables={"customers": customers, "orders": orders},
        primary_keys=keys,
        relationships=[("orders.customer", "customers.customer_id")],
    )
except SchemaError as error:
    show(error)
```

```text
SchemaError: Table 'orders' has no column 'customer'.
```

Relationships are written child first, as `"table.column"`. When the table
name is misspelled in `entity=`, the error lists the available tables; in a
relationship it does not, so check the spelling against `db.describe()`.

## Fitting and predicting

### Keys in X that are not in the entity table

```python
from sklink.exceptions import UnknownEntityError
from sklink.tree import RelationalDecisionTreeClassifier

db = Database(
    tables={"customers": customers, "orders": orders},
    primary_keys=keys,
    relationships=links,
)
X = pd.DataFrame({"customer_id": [1, 2, 3]})
y = [1, 1, 0]
tree = RelationalDecisionTreeClassifier(db, entity="customers", key="customer_id").fit(
    X, y
)
try:
    tree.predict(pd.DataFrame({"customer_id": [4]}))
except UnknownEntityError as error:
    show(error)
```

```text
UnknownEntityError: 1 rows of X have keys that do not exist in table 'customers'. Pass handle_unknown_entity='empty' to treat them as entities without related rows.
```

A new customer whose row is not in the database yet cannot be looked up.
Add the row, or pass `handle_unknown_entity="empty"` to predict it as a
customer without orders.

### The key column is missing from X

```python
try:
    RelationalDecisionTreeClassifier(db, entity="customers", key="id").fit(X, y)
except ValueError as error:
    show(error)
```

```text
ValueError: key column 'id' not found in X. Available columns: ['customer_id'].
```

`key` names the column of `X` that holds the entity's key, which need not
have the same name as the primary key in the database.

Inside `BaggingClassifier`, keep `max_features=1.0` and
`bootstrap_features=False`: otherwise the columns of `X` are subsampled and
the key column can be dropped or moved.

### A saved model without its tables

```python
import sklink
from sklink.exceptions import DetachedDatabaseError

saved = sklink.detach(tree)
try:
    saved.predict(X)
except DetachedDatabaseError as error:
    show(error)
```

```text
DetachedDatabaseError: This model was detached from its database. Call sklink.rebind(model, database) before using it.
```

`sklink.detach` removes the tables before you save a model. Attach the data
you want to predict from with `sklink.rebind(model, database)`. See
[save and deploy](../tutorials/save-and-deploy).

## Time and cutoffs

### A table without a time column in temporal mode

```python
import warnings

X_at = X.assign(cutoff=pd.Timestamp("2024-06-01"))
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    RelationalDecisionTreeClassifier(
        db, entity="customers", key="customer_id", time="cutoff"
    ).fit(X_at, y)
for warning in caught:
    print(f"{warning.category.__name__}: {warning.message}")
```

```text
SklinkWarning: Temporal mode: tables ['orders'] have no time column and are not reached through one, so all their rows are visible at every cutoff.
```

With `time=`, only rows dated before each cutoff are visible, so every
table that changes over time needs a time column:
`Database(..., time_columns={"orders": "created_at"})`. Static tables, such
as a product catalog, can stay without one; the warning lists them so you
can check.

### Predicting without the cutoff column

```python
dated = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", time="cutoff"
).fit(X_at, y)
try:
    dated.predict(X)
except ValueError as error:
    show(error)
```

```text
ValueError: The feature names should match those that were passed during fit.
Feature names seen at fit time, yet now missing:
- cutoff
```

The message comes from scikit-learn and says only that a column is missing:
here it is the column you passed as `time=`. A model fitted with cutoffs
needs one at prediction time too: usually the date you predict on.

## Warnings worth reading

* **`LeakageWarning`**: a setting can let one sample read another sample's
  rows, such as `allow_reverse_paths=True` without cutoffs. Check that this is
  what you meant before trusting a score.
* **`PerformanceWarning`**: an operation will be slow or use much memory,
  such as pickling a model that still holds large tables. The message says
  what to do instead, here `sklink.detach`.

All warnings derive from `sklink.exceptions.SklinkWarning`, so you can filter
them in one line:

```python
import warnings
from sklink.exceptions import SklinkWarning

warnings.filterwarnings("ignore", category=SklinkWarning)
```

## Still stuck?

[Open an issue](https://github.com/rodrigo-arenas/scikit-link/issues) with
the message, `sklink.show_versions()` and a small example.
