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:
- 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.
- Normalise — de-duplicate and rewrite as a single-column file. Your original CSV is never uploaded.
- Upload to a
uuid4-suffixed prefix under theS3Storageyou passed. - Create the external table over that prefix, in the database you named.
- Yield a
StagedTablefor you to query against. - 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
DROPor 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 anahi_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 loginbeforehand (local SSO), or run where an AWS role is attached (EC2 instance role, ECS task role); missing or expired credentials raiseAuthErrorwith the command to run. No default region: setAWS_REGIONor the profile'sregion. - Parameterized queries by default. Pass values via
parameters(named:namefor Redshift, positional?for Athena) — never format them in. - One synchronous call.
run_querysubmits, polls with backoff (seeahi.core.poll_until), and pages the full result set, returning aQueryResultyou 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 raisePollTimeoutError. - S3 transfers return
S3Objectrecords (bucket, key, local path, size); failures raiseUploadFailedError/DownloadFailedError/DeleteFailedError. - Staging cleans up after itself.
stage_id_tabledrops the table and deletes the staged files on exit, including when the body raises. It builds nothing itself: theAthenaClientandS3Storageare injected, so there is no hidden region or credential handling, and the DDL comes fromahi.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.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ahi_aws-0.4.2.tar.gz | 32.4 kB | Without provenance | Details for ahi_aws-0.4.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ahi_aws-0.4.2-py3-none-any.whl | Python 3 | none | any | Details for ahi_aws-0.4.2-py3-none-any.whl |
Total release size: 57.1 kB
Release files / ahi_aws-0.4.2.tar.gz
| Download URL | ahi_aws-0.4.2.tar.gz |
|---|---|
| Size | 32.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e459c12673bc3dbced64fbc04f378d6e634a4df62701e6a3046fee1dd95e6604
|
|
BLAKE2b-256 checksum How to use checksums |
58fce9a90399c931b0eacd222de777385e465889430485a5d4a441cc824e5eed
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / ahi_aws-0.4.2-py3-none-any.whl
| Download URL | ahi_aws-0.4.2-py3-none-any.whl |
|---|---|
| Size | 24.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
50c92ec714ba1de40b30861045dc83600073ae4df7304b5238b3234b59b6ca74
|
|
BLAKE2b-256 checksum How to use checksums |
032837714ed5ee4b3b6607ed8475d770915ea8df69eee5daf4f1389771173af9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for ahi-aws 0.4.2
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.