Metadata-Version: 2.5
Name: ahi-aws
Version: 0.4.2
Summary: Thin, typed boto3 helpers for AHI: AWS auth (SSO and attached-role sessions), Redshift Data API and Athena query execution, and S3 file storage.
Project-URL: Homepage, https://adaptivehealthintelligence.github.io/ahi-python-packages/
Project-URL: Documentation, https://adaptivehealthintelligence.github.io/ahi-python-packages/
Author: Adaptive Health Intelligence
License: MIT
Keywords: ahi,athena,auth,aws,boto3,redshift,s3,sso,sts
Requires-Python: >=3.11
Requires-Dist: ahi-core<0.3,>=0.2
Requires-Dist: ahi-sql<0.3,>=0.2.1
Requires-Dist: boto3>=1.34
Provides-Extra: types
Requires-Dist: boto3-stubs[athena,redshift-data,s3,sts]>=1.34; extra == 'types'
Description-Content-Type: text/markdown

# ahi-aws

Thin, typed `boto3` helpers for AHI. Today: AWS **auth** (one session, checked
once, with clear errors), running SQL on **Redshift** (Data API) and **Athena**,
with async query handling, moving files and folders to and from **S3**, and
**staging a list of IDs** so Athena can join against it server-side.

```python
from ahi.aws.auth import aws_session, check_identity

session = aws_session()  # AWS_PROFILE / default profile / attached role
identity = check_identity(session)  # raises an AuthError saying what to run
print(identity.arn, identity.method)  # e.g. "sso", "iam-role", "container-role"
```

```python
from ahi.aws.redshift import RedshiftDataClient
from ahi.aws.athena import AthenaClient

rs = RedshiftDataClient(workgroup_name="analytics", database="dev")
rows = rs.run_query(
    "select count(*) from events where day = :day",
    parameters={"day": "2026-06-26"},
)
print(rows.scalar())

ath = AthenaClient(workgroup="primary", database="analytics")
for row in ath.run_query("select name from users where id = ?", parameters=[42]):
    print(row["name"])
```

```python
from ahi.aws.auth import aws_session
from ahi.aws.s3 import S3Storage

session = aws_session()
storage = S3Storage("s3://my-bucket/some/prefix", client=session.client("s3"))

uploaded = storage.upload_dir("runs/run-01", prefix="run-01")  # list[S3Object]
storage.download_dir("run-01", "local/run-01")
```

## Joining against a list of IDs

Filtering an Athena table by a long list of IDs can't be done with a generated
`IN (...)` clause: Athena caps query text at 262,144 bytes, which around 100k
IDs exceeds. `stage_id_table` puts the IDs in S3 instead, registers a table over
them, and lets Athena do the join.

**The steps it performs, in order:**

1. **Validate** the CSV in full — one chosen column, a usable header, every
   value a non-blank integer. Nothing reaches AWS until this passes, so a bad
   file costs nothing.
2. **Normalise** — de-duplicate and rewrite as a single-column file. Your
   original CSV is never uploaded.
3. **Upload** to a `uuid4`-suffixed prefix under the `S3Storage` you passed.
4. **Create** the external table over that prefix, in the database you named.
5. **Yield** a `StagedTable` for you to query against.
6. **Tear down** on exit — drop the table, delete the staged files. This runs
   even when the body raises; a teardown failure is logged rather than allowed
   to mask your error.

```python
from ahi.aws import AthenaClient, S3Storage, stage_id_table
from ahi.aws.auth import aws_session

session = aws_session()
athena = AthenaClient(workgroup="primary", database="analytics")
storage = S3Storage("s3://my-bucket/scratch", client=session.client("s3"))

with stage_id_table(
    "encounter_ids.csv",  # CSV with a header row
    athena=athena,
    storage=storage,
    database="scratch",  # scratch database the table is created in
    column="encounter_id",  # header name, 0-based index, or omit for a 1-column file
) as staged:
    result = athena.run_query(
        f"SELECT e.encntr_id, e.facility "
        f"FROM encounter e "
        f"JOIN {staged.table} i ON e.encntr_id = i.{staged.column} "
        f"WHERE e.year = ? AND e.month = ? AND e.day = ?",
        parameters=[2026, 11, 9],
    )
```

The staged column is `bigint`, so an integer join key needs no `CAST`.
`staged.table` is quoted and database-qualified, so it drops into a query
running against any other database.

### Checking it worked

**1 — no exception was raised.** The context manager raises on every staging
failure, so a `with` block that is entered at all has already proved the CSV
validated, the file uploaded and the table was created. There is nothing to
assert: if you reach the first line of the block, those three steps succeeded.
A failure surfaces as `InvalidIdFileError` (bad CSV), `UploadFailedError` (S3)
or `QueryFailedError` (the `CREATE`), never as a silently empty table.

**2 — the right number of IDs was staged.** `staged.rows` is the distinct count
after de-duplication, so it is at most your CSV's data-row count:

```python
print(f"{staged.rows} distinct ids staged from {csv_path}")
```

**3 — Athena can see them.** Read the table back inside the block; it should
match `staged.rows` exactly. If it returns 0, the table was created but the
files aren't where it is looking:

```python
staged_count = int(athena.run_query(f"SELECT count(*) FROM {staged.table}").scalar())
assert staged_count == staged.rows, f"{staged_count} in table, {staged.rows} staged"
```

**4 — the join matched what you expected.** Collect the **distinct** IDs that
came back and compare against what you submitted:

```python
returned = {int(row["encntr_id"]) for row in result}
print(f"{len(returned)} of {staged.rows} ids matched")
```

Use a set rather than `len(result)`: `encounter` can hold several rows for one
encounter ID on a run date, so a row count overstates the match. This check is
what separates two failures that otherwise look identical:

| What you see | What it means |
| ------------ | ------------- |
| Fewer matched than submitted | Normal — those IDs aren't in that partition. |
| Zero matched, but check 3 was healthy | Staging worked; the problem is your join predicate or the `year`/`month`/`day` filter. |
| Zero matched, and check 3 was zero | Staging failed — the table exists but Athena can't read the files. |

When something goes wrong, pass `keep=True` to leave the table and files in
place and inspect them directly:

```python
with stage_id_table(path, athena=athena, storage=storage, database="scratch", keep=True) as staged:
    print(staged.table, staged.location)  # still there after the block exits
```

> **On leftovers.** You don't need to check for these after a successful run: a
> `DROP` or delete that fails on the way out raises, so a block that returns
> cleanly has already torn itself down. They are only possible when the block
> *also* raised — teardown failures are logged rather than raised there, so they
> can't mask your original error — or when the process was killed before
> teardown ran. Both leave an `ahi_ids_*` table and prefix behind, so a periodic
> sweep of the scratch database and location is worth having:
>
> ```sql
> SHOW TABLES IN scratch 'ahi_ids_*'
> ```
>
> ```bash
> aws s3 ls s3://my-bucket/scratch/ --recursive
> ```

**Prerequisites:** the scratch database must already exist — this does not
create it. The role needs `s3:PutObject`, `s3:DeleteObject` and `s3:ListBucket`
on the scratch location, plus Athena rights to create and drop tables there.

**Failures:** an unusable CSV raises `InvalidIdFileError` with `.path`,
`.reason` and the 1-based `.row` at fault:

```python
from ahi.aws import InvalidIdFileError

try:
    with stage_id_table(path, athena=athena, storage=storage, database="scratch") as staged:
        ...
except InvalidIdFileError as exc:
    log.error("line %s: %s", exc.row, exc.reason)
```

> Only single-column integer IDs are supported. A general typed, multi-column
> version is future work.

## Design notes

- **Never logs in for you.** No browser, no AWS CLI. Run `aws sso login`
  beforehand (local SSO), or run where an AWS role is attached (EC2 instance
  role, ECS task role); missing or expired credentials raise `AuthError`
  with the command to run. No default region: set `AWS_REGION` or the
  profile's `region`.
- **Parameterized queries by default.** Pass values via `parameters` (named
  `:name` for Redshift, positional `?` for Athena) — never format them in.
- **One synchronous call.** `run_query` submits, polls with backoff (see
  `ahi.core.poll_until`), and pages the full result set, returning a
  `QueryResult` you can iterate, `len()`, or call `.scalar()` on.
- **Typed results from Redshift; strings from Athena** (Athena returns all values
  as strings — we preserve that rather than guessing).
- **Failures raise** `QueryFailedError`; timeouts raise `PollTimeoutError`.
- **S3 transfers return `S3Object` records** (bucket, key, local path, size);
  failures raise `UploadFailedError` / `DownloadFailedError` / `DeleteFailedError`.
- **Staging cleans up after itself.** `stage_id_table` drops the table and
  deletes the staged files on exit, including when the body raises. It builds
  nothing itself: the `AthenaClient` and `S3Storage` are injected, so there is
  no hidden region or credential handling, and the DDL comes from `ahi.sql`.

Install the optional `types` extra (`ahi-aws[types]`) for `boto3-stubs` during
development.

Part of [ahi-python-packages](https://github.com/adaptivehealthintelligence/ahi-python-packages).
