# Tabular knowledge

How Excel and CSV knowledge files are normalized into SQL tables and queried by agents without vector search.

Spreadsheets are not documents made of paragraphs. Sending a workbook through the
document parser produces hundreds of chunks whose text is `cell | cell | cell`,
which pollutes semantic search and still cannot answer "what is the total COGM for
B000".

Pinter therefore treats tabular files (`csv`, `xlsx`, `xls`) as **data**, not text:

| Aspect | Tabular files | Other documents |
| --- | --- | --- |
| Parsed by | Normalizer in the backend (pandas) | Docling parser job |
| Stored for agents as | One SQL table per sheet | Text chunks |
| Indexed in Qdrant | **No** | Yes, with embeddings |
| Read by agents with | SQL (`/tables/query`) | `search_knowledge` |
| Status after upload | Immediately `ready` (0 chunks) | `pending` → `ready` |

> **Note:** This is deliberate: retrieval over spreadsheet rows returns plausible-looking noise, while a `GROUP BY` returns the exact number. Tabular documents are excluded from semantic search.

## What happens on upload

  
**Validate and store the raw file**

    The extension must be `csv`, `xlsx`, or `xls`, and the content must match the
    extension. The original file is stored unchanged at
    `knowledge/<asset_id>/v1_<filename>`.
  
  
**Skip the document parser**

    No parser job is submitted and no chunks or embeddings are created. The version
    is marked `ready` with `chunk_count = 0`, so the document appears as processed
    right away.
  
  
**Normalize on first access**

    The first time the document is opened — in the UI detail view or through an agent
    tool or route — the backend downloads the raw file and builds one SQL table per
    sheet. The result is cached in GCS as
    `knowledge/<asset_id>/tabular/<checksum>-v1.sqlite.gz`, so later requests on any
    replica skip the work.
  

Normalization for a typical report takes well under a second; a 72-sheet workbook
takes about 13 seconds on first access only.

## Normalization rules

Each worksheet becomes its own table, named after the sheet:

| Sheet title | Table name |
| --- | --- |
| `Urea Jawa` | `urea_jawa` |
| `(BP) Balans` | `bp_balans` |
| `123 Mulai Angka` | `t_123_mulai_angka` |

A workbook with a single sheet, and every CSV file, uses the table name `data`.

Column names are always quoted identifiers because real headers contain spaces and
parentheses (`"Stok Admin (Ton)"`, `"Beban Administrasi dan Umum"`).

The normalizer then applies these steps, recording every decision in the artifact
metadata:

| Step | What it does |
| --- | --- |
| Header detection | Finds the header row under the report title block instead of assuming row 1. |
| Two-level headers | Merges a group row above the header, e.g. `JAN` / `PKG` becomes `JAN PKG`. |
| Merged cells | Fills the first label column downward (`Kabupaten/Kota` on split rows). |
| Subtotal rows | Drops rows starting with `TOTAL`, `JUMLAH`, `SUBTOTAL`, `REKAP`. |
| Repeated headers | Drops header rows printed again in the middle of a long export. |
| Empty columns | Drops columns with no values and columns whose header is blank. |
| Type inference | `INTEGER` for whole numbers, `REAL` for decimals, `TEXT` otherwise; Indonesian formats like `1.234,56` are understood. |
| Mixed columns | A column mixing numbers and notes stays `TEXT` — summing it will error rather than invent a number. |

> **Warning:** Limits per document: 25 MB file, 500,000 rows, 1,000,000 cells, 500 columns, 100
> tables. Sheets that exceed a limit are skipped with a warning when the workbook has
> other usable sheets; a single oversized sheet fails the document with a clear
> message.

## Read tables as an agent

Agents never write SQL. They send a **structured query** — table, columns, filters,
aggregations — and the backend compiles it with validated identifiers and bound
parameters. That removes SQL injection entirely and keeps the model from inventing
functions or joins that do not exist.

Endpoints live under the knowledge document path and require the caller to have
**use** permission on the document.

```bash List tables
curl -s "$PINTER/api/knowledge/documents/hub-documents/$DOC_ID/tables" \
  -H "Authorization: Bearer $TOKEN" -H "API-Version: 1"
```

```bash Structured query
curl -s -X POST \
  "$PINTER/api/knowledge/documents/hub-documents/$DOC_ID/tables/select" \
  -H "Authorization: Bearer $TOKEN" -H "API-Version: 1" \
  -H "Content-Type: application/json" \
  -d '{
        "table": "summary_alokasi_fullcost_pkg",
        "group_by": ["ANPER"],
        "aggregations": [{ "fn": "sum", "column": "Qty Produksi", "as": "qty" }],
        "order_by": [{ "column": "qty", "direction": "desc" }],
        "limit": 10
      }'
```

```bash Preview rows
curl -s "$PINTER/api/knowledge/documents/hub-documents/$DOC_ID/tables/summary_alokasi_fullcost_pkg/rows?limit=50" \
  -H "Authorization: Bearer $TOKEN" -H "API-Version: 1"
```

`GET /tables` returns the schema the agent needs before querying:

```json
{
  "document_id": "0f3c…",
  "filename": "Summary Alokasi Fullcosting.xlsx",
  "table": "summary_alokasi_fullcost_pkg",
  "tables": [
    {
      "name": "summary_alokasi_fullcost_pkg",
      "total_rows": 930,
      "column_count": 22,
      "selected": true,
      "columns": [
        { "name": "ANPER", "type": "TEXT" },
        { "name": "PERIODE (Tahun)", "type": "INTEGER" },
        { "name": "COGM", "type": "REAL" }
      ],
      "values": {
        "ANPER": ["B000", "E000"]
      }
    },
    { "name": "summary_alokasi_fullcost_pkc", "total_rows": 386, "column_count": 22 }
  ],
  "sample": {
    "columns": ["ANPER", "PERIODE (Tahun)", "COGM"],
    "rows": [["B000", 2026, 1436060684.0]]
  }
}
```

Only the selected table carries its column list and value facets; the others are
listed by name and size. This keeps a 72-sheet workbook from flooding the model
context (a five-sheet workbook costs ~750 tokens instead of ~2,500).

`values` holds up to 20 distinct values for up to five low-cardinality `TEXT`
columns — the agent filters on real values (`"ANPER": "B000"`) instead of guessing
the spelling. `sample` is columnar so column names are not repeated per row.

### Query parts

| Field | Meaning |
| --- | --- |
| `table` | Table to read. Optional when the document has a single table (`data`). |
| `columns` | Columns to return. Ignored when `aggregations` is present. |
| `filters` | List of `{ "column", "op", "value" }`. |
| `group_by` | Columns to group by, used with `aggregations`. |
| `aggregations` | List of `{ "fn", "column", "as" }`. |
| `order_by` | List of `{ "column", "direction" }`; column may be a group column or an aggregate alias. |
| `limit` / `offset` | Page size (default 100, max 1000) and offset. |

Supported `op` values: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `in`, `not_in`,
`contains`, `starts_with`, `between`, `is_null`, `is_not_null`.

Supported `fn` values: `count`, `count_distinct`, `sum`, `avg`, `min`, `max`.
`sum` and `avg` are rejected on `TEXT` columns instead of returning a wrong number.

```json
{
  "table": "summary_alokasi_fullcost_pkg",
  "columns": ["ANPER", "COGM"],
  "filters": [
    { "column": "PERIODE (Tahun)", "op": "eq", "value": 2026 },
    { "column": "COGM", "op": "gte", "value": 1000000 }
  ],
  "order_by": [{ "column": "COGM", "direction": "desc" }],
  "limit": 20
}
```

The response is the same shape as the row preview:

```json
{
  "table": "summary_alokasi_fullcost_pkg",
  "columns": ["ANPER", "qty"],
  "rows": [["B000", 437202.0]],
  "row_count": 1,
  "truncated": false,
  "execution_ms": 1.2
}
```

`truncated: true` means more rows matched than `limit` allowed — raise `limit` or
paginate with `offset` instead of reporting the partial count as the total.

> **Note:** In chat, agents use the built-in tools `get_table_schema(document_id, table?)` and
> `query_table(document_id, table?, columns?, filters?, group_by?, aggregations?,
> order_by?, limit?)`. Same builder, same validation.

> **Warning:** `POST …/tables/query` still accepts raw SQL for analysts and integration tests that
> must express something the builder cannot (e.g. `CASE`, window functions). It is
> authenticated and runs read-only, but it is **not** offered to agents — keep it out
> of prompts and automations driven by a model.

## Compare raw and parsed data in the UI

The document detail view shows both representations, so you can confirm what
ingestion changed:

- **Parsed** — the normalized tables (header detected, subtotals removed, typed
  columns). When a workbook has several sheets, a selector switches between them.
- **Raw file** — the untouched grid, columns labelled `A`, `B`, `C`, including the
  title rows. Useful when a header was detected in the wrong place.

## Limits and errors

| Situation | Result |
| --- | --- |
| Document is not `csv`/`xlsx`/`xls` | `400` — not a tabular document |
| Caller lacks use permission | `403` |
| SQL is not a single read-only statement | `400` with the validator message |
| Table or column does not exist | `400` — SQLite reports `no such table` / `no such column` |
| File cannot be read or is over a size limit | `422` |
| Temporary storage failure | `503` |

## Known limitations

- Sheets that stack several unrelated tables vertically are read as one table; only
  the first header row is used.
- Duplicate column labels in the source get `_2`, `_3` suffixes when there is no
  group row above them to disambiguate.
- Dates are read as text; cast them in SQL when you need date arithmetic.
- Cells are read from the cached formula results stored in the workbook. A workbook
  that was never recalculated may show stale or empty values.
