Skip to main content

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.

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"
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"])
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.
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:

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:

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:

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:

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:

SHOW TABLES IN scratch 'ahi_ids_*'
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:

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.

Metadata

Release files for ahi-aws 0.4.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ahi-aws 0.4.1
File Size Uploaded Provenance Actions
ahi_aws-0.4.1.tar.gz 32.3 kB Without provenance Details for ahi_aws-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ahi-aws 0.4.1
File Interpreter ABI Platform Actions
ahi_aws-0.4.1-py3-none-any.whl Python 3 none any Details for ahi_aws-0.4.1-py3-none-any.whl

Total release size: 57.0 kB

Release files / ahi_aws-0.4.1.tar.gz

Download URL ahi_aws-0.4.1.tar.gz
Size 32.3 kB
Tags Source
SHA-256 checksum
How to use checksums
966dca1f8a02e5b1425d5e9abd289a4b2d6a84a5f681ce9ec982022a38284e33
BLAKE2b-256 checksum
How to use checksums
606e8d94ca2852fe4a384ad90f99cc3a0dda6e78a2ba33b4c2cd686b7a61f290
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.6 {"installer":{"name":"uv","version":"0.10.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / ahi_aws-0.4.1-py3-none-any.whl

Download URL ahi_aws-0.4.1-py3-none-any.whl
Size 24.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2cce84b7bcd9bfa635051022b4f183fe7662d4d9d41498a5752a057b39c64113
BLAKE2b-256 checksum
How to use checksums
ba757ee147184e827de6d965d12fe6ceb6e045c1f0982c1c4671a6d93e6b9b23
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.6 {"installer":{"name":"uv","version":"0.10.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for ahi-aws 0.4.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page