Skip to content

OpenConceptLab/ocl_issues#2991 | Azure storage uploads file objects and raises on failure - #1003

Merged
snyaggarwal merged 4 commits into
OpenConceptLab:masterfrom
filiperochalopes:fix/azure-compatible-upload-backend
Nov 23, 2026
Merged

snyaggarwal merged 4 commits into
OpenConceptLab:masterfrom
filiperochalopes:fix/azure-compatible-upload-backend

Conversation

@filiperochalopes

@filiperochalopes filiperochalopes commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR: The Azure storage backend now has upload() with the same contract as S3 and MinIO (returns 204, raises on failure), so map project input files, import files and repo files are stored on Azure instead of being silently dropped. Because failures now raise, exports clean up after a failed upload, and url_for() signs reads so the importer can fetch from a private container.

Closes OpenConceptLab/ocl_issues#2991

Scope started as Azure only, as agreed: the single _put() hook per backend from the issue's "Possible solution" is deferred to a follow-up PR tracked in OpenConceptLab/ocl_issues#3042, and no S3 or MinIO storage code (#973, #975) is touched.

Scope grew during review

The original fix was the Azure upload() plus letting its failures raise. Review of 6b336ec (@snyaggarwal) found two consequences of that fix that this PR now also covers, so its scope is wider than in its first version:

Added in review Why it belongs here Reach beyond the original Azure fix Commit
Export cleanup in core/common/utils.py Failures now raise on Azure, and write_export_file / write_csv_to_s3 then skipped os.chdir(cwd) and the temp cleanup All backends: the finally also covers failed uploads and failed serialization on S3 and MinIO, where the same flaw already existed. Behavior on success is unchanged c07beb11
Signed url_for() in azure.py The importer fetches cached inputs with url_for() over plain HTTP, so an upload that now succeeds would still fail to import from a private container (the Azure default) Every Azure read URL: export downloads, map project and repo file URLs are now SAS URLs valid for 7 days (read-only, download name as rscd) instead of unsigned. A connection without an account key keeps the unsigned URL 63ef0278

Also from review, test-only: dedicated UploadFailure / ExportUploadFailure exceptions so failure-propagation tests cannot pass on an unrelated error.

Still out of scope: see "Out of scope" below.


Root cause

  1. BlobStorage (core/services/storages/cloud/azure.py) had no upload(). Every service.upload(...) call fell through to the empty CloudStorageServiceInterface.upload stub and returned None. MapProject.update_input_file requires result == 204, so on Azure input_file_name was never saved. Importer uploads (importers/views.py, importers/importer.py) and repos/models.py silently stored nothing.
  2. BlobStorage._upload wrapped everything in a bare except and returned None, so a failed upload was invisible, and upload_base64 still returned the file name after a swallowed failure.
  3. (review) Once uploads raise, write_export_file and write_csv_to_s3 (core/common/utils.py) skipped os.chdir(cwd) and the temp cleanup, because both change the process working directory before uploading. The same flaw already existed on S3 and MinIO.
  4. (review) The importer reads cached inputs through url_for() over plain HTTP. Azure's url_for() returned an unsigned URL, so against a private container (the Azure default) an upload could succeed and the import still fail.

Main Changes

Area Files Description
Azure upload() core/services/storages/cloud/azure.py New upload(key, file_content, headers, metadata): streams the file object with upload_blob(overwrite=True) and returns 204.
Failures surface core/services/storages/cloud/azure.py Bare except removed from _upload; upload_file and upload_base64 now raise on failure like S3/MinIO.
Content type core/services/storages/cloud/azure.py upload() resolves it from headers, then S3-style ContentType metadata, then the key extension, then application/octet-stream (same precedence as MinIO.upload).
Signed reads core/services/storages/cloud/azure.py url_for() returns a one-week read-only SAS URL (with the download name when given); a connection without an account key keeps the unsigned URL.
Export cleanup core/common/utils.py write_export_file restores the working directory and removes its temp files in a finally around the whole export (body renamed _write_export_file); write_csv_to_s3 restores the directory in a finally.
Tests core/services/storages/cloud/tests.py, core/common/tests.py BlobStorageTest upload and url_for cases; StorageUploadContractTest over S3, MinIO and Azure with a dedicated UploadFailure; export and CSV cleanup tests with a dedicated ExportUploadFailure.

Totals by git diff --numstat origin/master...HEAD: 4 files, +354/-52.

Key Decisions

Decision Choice Rationale
Scope Azure storage first; review added export cleanup (all backends) and signed Azure reads S3/MinIO upload paths already work; a shared _put() refactor widens risk and is left for a second PR (as the issue recommends). The two review additions are consequences of making Azure uploads raise and succeed.
upload() content settings Real content type, no Content-Encoding _upload turns application/octet-stream into Content-Encoding: octet-stream, which is wrong for import files. _upload's behaviour for upload_file is unchanged (an existing test pins it).
Failure handling Let the Azure SDK exception propagate S3 propagates boto errors, MinIO wraps S3Error; wrapping adds nothing for Azure.
Behaviour change upload_file / upload_base64 now raise instead of returning None Requested by the issue. Azure's upload() never worked, so no working flow depends on the silent failure. Export zips (common/utils.py) now fail visibly.
Duplication Content-type resolver duplicated from MinIO.__content_type Folding it into a shared helper belongs to the unification PR, which touches MinIO.
Signed reads SAS with the account key of the connection, read-only, one week; no key keeps the unsigned URL Same lifetime as the S3 presigned URLs. SAS-token or identity based connections cannot sign, and a container that allows anonymous reads keeps working as before.
Export cleanup finally in write_export_file (whole export) and write_csv_to_s3 Covers a failure in serialization as well as in the upload, and keeps the exception for the caller.

Out of scope (follow-up: OpenConceptLab/ocl_issues#3042)

  • upload_file return values still differ (Azure blob URL, MinIO object name, S3 204); only logged or ignored by callers.
  • Single _put() hook per backend in CloudStorageServiceInterface, with one shared content type resolution (replaces the copy of MinIO.__content_type added here).
  • public_read is honored only by S3 today.

Not changed here: BlobStorage.copy() still passes an unsigned source URL to start_copy_from_url; the resource report in core/reports/models.py uses cd_temp() without uploading; the CSV temp directory is still not removed.

Verification

docker exec oclapi2-api-1 python manage.py test core.common.tests core.services core.map_projects --keepdb
docker exec -e EXPORT_SERVICE=core.services.storages.cloud.aws.S3 oclapi2-api-1 python manage.py test core.map_projects --keepdb
docker exec oclapi2-api-1 pylint -j2 core/common/utils.py core/common/tests.py core/services/storages/cloud/azure.py core/services/storages/cloud/tests.py
  • RED before each change: 7 failures + 1 error (Azure upload, S3 and MinIO contract cases already passed); 2 failures (upload raising leaves the process in the temp directory, export and CSV); 2 errors (signed url_for)
  • core.common.tests core.services core.map_projects: 392 tests, 8 failures. 6 are the same failures master shows in this container (5 in OpenIDAuthServiceTest, MinIOTest.test_minio_client_instantiated_with_env_vars; identical FAIL: set on master, checked by stashing the first round of changes). The other 2 (MapProjectListViewTest.test_post, MapProjectViewTest.test_put) patch aws.S3.upload while the container uses MinIO; with EXPORT_SERVICE=...aws.S3 core.map_projects passes (108 tests, OK)
  • pylint 10.00/10, git diff --check clean
  • Real Azure emulator (Azurite, official image), through get_export_service() with EXPORT_SERVICE=...azure.BlobStorage, 10/10 checks, re-run after the last commit:
    • MapProject.update_input_file records input_file_name (save mocked, no DB rows written) and the blob holds the bytes
    • blob content type text/csv, no content encoding
    • importer-style headers: 204, application/octet-stream, no content encoding
    • non-seekable stream (5 MiB + 123 B pipe) uploaded intact
    • upload_base64 returns logo.png and stores it; upload_file stores the export
    • upload, upload_file, upload_base64 against a missing container raise ResourceNotFoundError
  • Same probe on master: input_file_name stays empty and the blob does not exist (reproduces #2991)
  • Private container round trip on Azurite (container without public access, importer read path url_for -> requests.get(stream=True) -> ImporterUtils.fetch_to_file), 8/8 checks: upload 204; unsigned URL HTTP 409; signed url_for URL HTTP 200 with the uploaded bytes; tampered signature and another blob's signature HTTP 403; filename becomes Content-Disposition: attachment; filename="my export.zip"
  • Not tested: a real Azure Storage account (Azurite only), production, CI (not run from here)

Probe output (excerpt):

PASS unsigned URL is refused by the private container HTTP 409
PASS signed url_for() URL is readable over plain HTTP HTTP 200, query keys: ['se', 'sig', 'sp', 'sr', 'sv']
PASS Importer read path (url_for + fetch_to_file) returns the uploaded bytes
PASS a tampered signature is refused HTTP 403
SUMMARY 8 / 8 passed

…nd raises on failure

BlobStorage had no upload(), so every caller fell through to the interface stub and got None (MapProject.update_input_file never recorded the file). Add upload() with the S3/MinIO contract (204, raise on failure), drop the bare except in _upload so failures are no longer swallowed, and add contract tests over S3, MinIO and Azure.
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-18T14:30:23.103322Z
We couldn’t complete this review. Comment @codex review to try again.
6b336ec PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’d address the export cleanup regression before merging. The new Azure upload fixes the missing 204 that map projects depend on. The importer still needs an authenticated read path for private Azure containers.

OCL behavior S3 MinIO Azure in this PR
upload(stream) Boto3 managed upload, returns 204 put_object, returns 204. Uses remaining length or 10 MiB parts for an unknown-length stream. upload_blob(overwrite=True), returns 204. The SDK handles stream length and chunking.
Stream content type Forwards metadata as ExtraArgs; ignores headers Header, then metadata.ContentType, then extension, then octet-stream Same precedence as MinIO
upload_file(path) Returns 204 Returns object name Returns blob URL. ZIP exports still get the legacy Content-Encoding: zip.
upload_base64 with valid input Returns file name. The public ACL path still catches NoCredentialsError. Returns file name. Wraps SDK S3Error. Returns file name on success. SDK upload exceptions now propagate.
url_for Presigned GET Presigned GET Unsigned URL

The remaining upload return-value and metadata differences are already tracked in #3042. SDK references: Boto3 managed uploads, MinIO stream uploads, Azure Blob uploads.

I reproduced the CSV working-directory leak by running the actual export helper with an injected upload exception. The Azure, S3, and MinIO comparison is based on source and SDK docs.

Comment thread core/services/storages/cloud/azure.py Resolved
Comment thread core/services/storages/cloud/azure.py Resolved
Comment thread core/services/storages/cloud/tests.py Resolved
…irectory and remove their temp files

write_export_file and write_csv_to_s3 change the process working directory before uploading. An upload that raises (now also on Azure) skipped os.chdir(cwd) and the temp cleanup. write_export_file now restores the directory and removes the temp files in a finally around the whole export; write_csv_to_s3 restores the directory in a finally. Regression tests assert the upload exception reaches the caller.
…so private containers can be read

The importer fetches cached inputs over plain HTTP through url_for(). Azure returned an unsigned URL, so an upload could succeed and the import still fail against a private container (the Azure default). url_for now returns a one-week read-only SAS URL for the blob, carrying the download name when given, and keeps the unsigned URL when the connection has no account key. Storage failure tests use a dedicated exception so they cannot pass on an unrelated error.
@filiperochalopes

Copy link
Copy Markdown
Contributor Author

Review round on 6b336ec, addressed in two new commits (no amend) on top of the current branch head:

# Item Result Commit
1 P2: restore export process state when an Azure upload raises Done. write_export_file restores the working directory and removes its temp files in a finally around the whole export; write_csv_to_s3 restores the directory in a finally. Tests assert the dedicated exception reaches the caller (they failed before the change). c07beb1
2 Private containers: url_for() is unsigned, the importer reads over plain HTTP Done. url_for() returns a one-week read-only SAS URL (download name via rscd); a connection without an account key keeps the unsigned URL. Verified on Azurite with a container without public access, through the importer read path: unsigned URL HTTP 409, signed HTTP 200 with the same bytes, tampered signature HTTP 403. 63ef027
3 Nit: dedicated test exception Done. UploadFailure in the storage tests, ExportUploadFailure in the export tests. 63ef027

The three review threads have a reply and are resolved. The PR body has the new root causes, decisions and verification numbers.

Not covered: a real Azure Storage account (Azurite only), BlobStorage.copy() (still an unsigned source URL), and the upload return-value and metadata differences already tracked in OpenConceptLab/ocl_issues#3042. Run in the local container: core.common.tests core.services core.map_projects shows 8 failures, 6 of them identical on master and 2 (MapProject test_post and test_put) that patch aws.S3 while the container uses MinIO; with EXPORT_SERVICE=...aws.S3 core.map_projects passes (108 tests).

@filiperochalopes filiperochalopes self-assigned this Nov 20, 2026

@snyaggarwal snyaggarwal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving at 63ef027. All three items from my Nov 20 review are fixed as your replies describe:

  • Export cleanup: write_export_file now runs the export inside a try/finally. The finally restores the working directory and removes the temp directory cd_temp() created (the same one the old code removed), and that also covers the export's early returns and a failed serialization. write_csv_to_s3 restores the directory in a finally before re-raising. The tests check that the dedicated ExportUploadFailure reaches the caller and that os.getcwd() is unchanged.
  • Private containers: url_for signs a read-only SAS (sp=r, 7 days like the S3 and MinIO presigned URLs) when the connection has an account key, and carries the download name through content_disposition_header. Without a key, it keeps the unsigned URL. Every caller (export downloads, map project and repo files, the importer's cached inputs) builds the URL when it's requested and none stores it, so the expiry matches S3's. Thanks for the Azurite round trip: 409 unsigned, 200 signed, 403 tampered.
  • Tests: the dedicated UploadFailure and ExportUploadFailure exceptions close the false-green path.

upload() streams with the same content-type precedence as MinIO, and _upload no longer swallows errors. That matches S3: a failed upload_base64, such as a logo, now raises instead of saving a name for a blob that was never written.

The branch is 23 commits behind master but merges cleanly. The only change to these files since (#985 in core/common/utils.py) is in other functions. CI was green on Nov 20. I haven't run the tests.

Fine as follow-ups: copy() still passes an unsigned source URL (same-account Shared Key copies don't need a SAS, but a SAS-only connection would), the CSV temp directory is still left behind as before, and the shared _put() refactor stays with #3042.

@snyaggarwal
snyaggarwal merged commit 29c1c25 into OpenConceptLab:master Nov 23, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Storage backends implement the upload contract inconsistently (Azure also lacks upload())

2 participants