ahi-aws¶
Thin, typed boto3 helpers. Today it covers AWS auth (one session,
checked once, with clear errors), running SQL on Redshift (via the Data API)
and Athena, and moving files to and from S3. Both query
clients hide the asynchronous submit → poll → page dance behind a single
synchronous run_query that returns a QueryResult.
uv add ahi-aws
Auth¶
ahi.aws.auth gives every app the same way to get AWS credentials, and the
same code runs on a laptop with SSO and on a machine with an attached role:
there is nothing to switch. It never logs in for you (no browser, no AWS CLI):
if credentials are missing or expired it raises an AuthError
saying what to run.
from ahi.aws.athena import AthenaClient
from ahi.aws.auth import aws_session, check_identity
session = aws_session() # boto3's standard resolution; no profile to configure
identity = check_identity(session) # one sts:GetCallerIdentity call
log.info("AWS: %s via %s", identity.arn, identity.method) # e.g. "via sso"
athena = AthenaClient(workgroup="primary", client=session.client("athena"))
Create the session once per run and pass session.client(...) to the other
helpers. SSO and role credentials are refreshable, so botocore renews them for
you during a long run.
Local SSO (a person at a machine)¶
- Once:
aws configure ssoto create a profile (make it your default, or setAWS_PROFILE=<name>in your shell or the app's local.env). - Before a run:
aws sso login(add--profile <name>for a named profile). - Run the app.
identity.methodis"sso".
Attached role (EC2, ECS/Fargate, scheduled jobs)¶
Attach an IAM role to the resource (an EC2 instance profile, or an ECS task role) and give the role the permissions the app needs. Then:
- Leave
AWS_PROFILEunset. Don't copy a developer's.envthat sets it: boto3 would look for that profile and fail instead of using the role. - Set
AWS_REGION(orAWS_DEFAULT_REGION). boto3 does not read the region from the instance.
No login and no profile: boto3's default credential chain finds the role.
identity.method is "iam-role" on EC2 and "container-role" on ECS/Fargate.
Where credentials and region come from¶
Credentials: the first source that contain them is used; later sources are never checked.
| Order | Source | Where it applies |
|---|---|---|
| 1 | Keys in the environment (AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY) |
Not used at AHI; unset them, or they override everything below |
| 2 | The profile in use: AWS_PROFILE, else [default] in ~/.aws |
Dev laptop with an SSO login |
| 3 | The attached role: ECS/Fargate task role, else EC2 instance role | EC2, ECS and scheduled jobs |
aws_session(profile="name") skips this list and uses only that profile. If
you pass one, it must exist on the machine running the code, or
aws_session raises ProfileNotFoundError; on machines that use an attached
role (EC2, ECS), pass None. Long-term access keys are not a supported way to
run.
Region: the first of aws_session(region=...), AWS_REGION,
AWS_DEFAULT_REGION, the profile's region. There is no default region,
and boto3 does not read the EC2 instance's region; if none resolves,
aws_session raises RegionNotConfiguredError.
Auth errors¶
Every failure is an AuthError (a subclass of ahi.core.AhiError) carrying
.profile, .reason (the botocore message) and .hint (what to do), raised
from the original botocore error, so a traceback still shows botocore's exact
point of failure.
The message never hides botocore's detail. It has three parts: what went wrong, what botocore said, and what to do:
AWS SSO login is missing or expired (botocore: Error loading SSO Token: Token for https://example.awsapps.com/start does not exist). Run `aws sso login --profile my-profile`, then retry.
The botocore part is left out only when no botocore error is behind the failure (for example no region configured). Each cause has its own subclass:
| Error | Cause | Message / what to do |
|---|---|---|
ProfileNotFoundError |
Profile not configured | "AWS profile 'X' is not configured": check AWS_PROFILE (leave it unset on a machine with a role), or run aws configure sso. |
SsoLoginRequiredError |
SSO login missing or expired | Run aws sso login (with --profile X for a named profile), then retry. |
CredentialsNotFoundError |
No credentials at all | Log in with aws sso login, or run where an AWS role is attached. |
CredentialsRejectedError |
AWS rejected them (ExpiredToken, InvalidClientTokenId, AccessDenied) |
The AWS error code, plus where the credentials came from. Also has .code, .method and .expired. |
RegionNotConfiguredError |
No region | Set AWS_REGION, add region to the profile, or pass region=. |
AwsUnreachableError |
Network, proxy or SSL failure | "Cannot reach AWS STS in .region. |
AuthError itself |
Anything else botocore raises | Check aws configure list. |
Catch the base to show the message, or a subclass to act on one cause:
from ahi.aws import AuthError, AwsUnreachableError
try:
identity = check_identity(aws_session())
except AwsUnreachableError:
... # a scheduled job might retry later
except AuthError as exc:
# e.g. "AWS SSO login is missing or expired (botocore: ...). Run `aws sso login`, then retry."
raise SystemExit(str(exc))
Redshift¶
RedshiftDataClient uses the Redshift Data API, so it needs no driver, no open
connection, and no VPC access — just IAM. It targets Redshift Serverless (a
workgroup) or a provisioned cluster.
from ahi.aws.redshift import RedshiftDataClient
client = RedshiftDataClient(
workgroup_name="analytics", # or cluster_identifier="my-cluster"
database="dev",
)
result = client.run_query(
"select count(*) as n from events where day = :day",
parameters={"day": "2026-06-26"}, # named params -> :day
)
print(result.scalar()) # 1234
for row in client.run_query("select id, name from users"):
print(row["id"], row["name"])
Authentication to the database follows whatever your cluster uses — the
workgroup's default IAM auth, db_user (provisioned temp credentials), or
secret_arn (Secrets Manager):
RedshiftDataClient(cluster_identifier="prod", database="dev", db_user="analyst")
RedshiftDataClient(
workgroup_name="analytics", database="dev", secret_arn="arn:aws:secretsmanager:..."
)
Athena¶
from ahi.aws.athena import AthenaClient
client = AthenaClient(workgroup="primary", database="analytics")
rows = client.run_query(
"select name from users where id = ?", # positional ? placeholders
parameters=[42],
)
for row in rows:
print(row["name"])
Result location and encryption are normally configured on the workgroup. If
yours doesn't enforce one, pass output_location="s3://my-bucket/athena/".
Athena returns strings
Athena reports every value as a string (or None for NULL). The wrapper
preserves that rather than guessing types — cast in SQL or in your code.
QueryResult¶
Both clients return the same object:
result.columns # ['id', 'name']
result.rows # [{'id': 1, 'name': 'alice'}, ...]
result.query_id # service-assigned id (handy for logs)
len(result) # row count
list(result) # iterate rows (dicts)
result.scalar() # the single value of a 1x1 result; raises otherwise
S3 storage¶
S3Storage uploads and downloads files under an s3://bucket/prefix
location. You can pass in additional Keys and prefixes which are appended to the base location.
S3Storage accepts a client from a boto3.Session, usually the one from
aws_session(). It will create a default session if none is provided.
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"))
storage.upload_file("report.pdf") # -> s3://my-bucket/some/prefix/report.pdf
storage.upload_file("report.pdf", key="reports/2026.pdf")
uploaded = storage.upload_dir("runs/run-01", prefix="run-01")
for obj in uploaded:
print(obj.uri, obj.size, obj.local_path)
storage.download_file("run-01/report.pdf", "local/report.pdf")
downloaded = storage.download_dir("run-01", "local/run-01")
| Method | Does |
|---|---|
upload_file(path, key=None) |
Upload one file; the key defaults to the file name. |
upload_dir(path, prefix="") |
Upload every file under a folder, keeping its layout. Keys always use /, also on Windows. |
download_file(key, path) |
Download one object, creating parent folders and overwriting path. |
download_dir(prefix, path) |
Download every object under a prefix into a folder, keeping its layout. |
delete_file(key) |
Delete one object. Succeeds if it is already absent. |
delete_prefix(prefix) |
Delete every object under a prefix; returns how many. The prefix is required. |
Each returns an S3Object (or a list of them) with bucket, key,
local_path, size and uri, so you can record what went where.
Transfers use boto3's managed transfer: files of 8 MiB or more go multipart
automatically (10 parallel threads) and parts are retried. Tune it with
transfer_config:
from boto3.s3.transfer import TransferConfig
S3Storage(
"s3://my-bucket/some/prefix",
client=session.client("s3"),
transfer_config=TransferConfig(multipart_threshold=64 * 1024**2, max_concurrency=4),
)
The folder methods work in a fixed order and stop at the first failure. Files already transferred stay where they are, and running again overwrites them, so a retry is safe. S3 overwrites existing keys silently, so give each run its own prefix.
Permissions¶
| Operation | IAM actions |
|---|---|
| Upload | s3:PutObject |
| Download | s3:GetObject |
download_dir (listing) |
s3:ListBucket |
| Delete | s3:DeleteObject (plus s3:ListBucket for delete_prefix) |
S3 errors¶
Failures raise UploadFailedError, DownloadFailedError or
DeleteFailedError. All are
S3Error (an ahi.core.AhiError), carrying .bucket, .key, .reason and
.code. The code is the S3 error code, such as "AccessDenied", or "404"
for a missing key. Missing or expired credentials are wrapped too, with
.code = None and botocore's message as the reason.
from ahi.aws import UploadFailedError
try:
storage.upload_dir(run_dir, prefix=run_id)
except UploadFailedError as exc:
log.error("upload to %s failed (%s): %s", exc.key, exc.code, exc.reason)
Staging IDs for a server-side join¶
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 a list of
around 100,000 IDs exceeds. stage_id_table puts the IDs in S3 instead,
registers a table over them, and lets Athena do the join.
from ahi.aws import AthenaClient, S3Storage, stage_id_table
athena = AthenaClient(workgroup="primary", database="analytics")
storage = S3Storage("s3://my-bucket/scratch", client=session.client("s3"))
with stage_id_table(
"encounter_ids.csv", athena=athena, storage=storage, database="scratch"
) as staged:
result = athena.run_query(
f"SELECT e.encntr_id, e.facility "
f"FROM encounter e "
f"JOIN {staged.table_ref} i ON e.encntr_id = i.{staged.column_ref} "
f"WHERE e.year = ? AND e.month = ? AND e.day = ?",
parameters=[2026, 11, 9],
)
print(f"{len(result)} of {staged.rows} ids matched")
On leaving the block the table is dropped and the staged files are deleted —
including when the body raises. Pass keep=True to leave both in place while
debugging.
| Argument | Does |
|---|---|
path |
Local CSV. Must have a header row. |
athena |
Client used to run the CREATE and DROP. |
storage |
Where the staged file goes; the table gets a unique sub-prefix of this location. |
database |
Database to create the table in — usually a scratch database, not the one queried. |
column |
Header name, 0-based index, or None to require a single-column file. |
keep |
Leave the table and files in place on exit. |
The StagedTable yielded by the block carries table_ref (quoted and
database-qualified, so it drops into a query against any database),
column_ref, column, location and rows.
The column name comes in two forms, because one can't do both jobs:
| Writing | Use | Produces |
|---|---|---|
SQL — a join, WHERE, a SELECT list |
staged.column_ref |
i."encounter_id" |
| Python — a result-row key, a log message | staged.column |
row["encounter_id"] |
A header such as enc-id is valid but unquoted becomes i.enc-id, which
Athena parses as subtraction; quoted as a result key it raises KeyError,
since Athena returns keys unquoted. table_ref and column_ref are both the
SELECT form — the CREATE and DROP quote the name themselves, with
backticks.
Checking it worked¶
| Check | How | What it tells you |
|---|---|---|
| The right IDs were staged | staged.rows |
Distinct count after de-duplication — at most your CSV's data-row count. |
| Athena can see them | SELECT count(*) FROM {staged.table_ref} |
Should equal staged.rows. A 0 here means the table exists but the files aren't where it is looking. |
| The join did something | len(result) vs staged.rows |
Fewer is normal — not every ID exists in the partition. Zero, with a healthy staged count, points at the join predicate or partition filter rather than at staging. |
| Nothing was left behind | SHOW TABLES IN scratch 'ahi_ids_*', aws s3 ls on the scratch prefix |
Both should be empty after the block. A leftover means teardown failed — the warning is in the logs. |
with stage_id_table(csv_path, athena=athena, storage=storage, database="scratch") as staged:
staged_count = int(athena.run_query(f"SELECT count(*) FROM {staged.table_ref}").scalar())
assert staged_count == staged.rows, f"{staged_count} in table, {staged.rows} staged"
result = athena.run_query(...)
returned = {int(row["encntr_id"]) for row in result}
print(f"{len(returned)} of {staged.rows} ids matched")
When something goes wrong, keep=True leaves the table and files in place so
you can inspect them after the block exits.
What gets staged¶
Values are validated, de-duplicated and rewritten as a single-column file before
upload — the original CSV is never sent. The staged column is bigint, so a
join against an integer key needs no CAST.
Validation runs in full before anything reaches AWS, so a bad file costs
nothing. An unusable file 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)
A file is rejected when it is empty, has only a header, has more than one column
with no column= given, names a column that isn't there, or holds a value that
is blank or not an integer. Column headers are lowercased and must be plain
identifiers (letters, digits, underscore and hyphen, not starting with a digit).
Single integer column only
A general version taking several columns with declared types is future work.
Permissions
Staging needs s3:PutObject, s3:DeleteObject and s3:ListBucket on the
scratch location, and Athena rights to create and drop tables in the scratch
database. The database itself must already exist.
Errors & timeouts¶
- A query that ends in a failed state raises
QueryFailedError(a subclass ofahi.core.AhiError) carrying.query_id,.state, and.reason. - A query that doesn't finish within
timeout(default 300s) raisesPollTimeoutError. Tune per call:run_query(sql, timeout=900, poll_interval=2).
from ahi.aws import QueryFailedError
from ahi.core import PollTimeoutError
try:
client.run_query(sql, timeout=120)
except QueryFailedError as exc:
log.error("query %s failed: %s", exc.query_id, exc.reason)
except PollTimeoutError:
log.warning("query still running after 120s")
Type stubs¶
For editor/CI type-checking of the boto3 surface, install the optional extra:
uv add "ahi-aws[types]" # adds boto3-stubs[athena,redshift-data,s3,sts]