Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions SPRINTLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -711,3 +711,4 @@ _Nothing merged during this sprint_

- Bump dnspython from 2.9.0 to 2.9.2 ([#1893]https://github.com/ScilifelabDataCentre/dds_web/pull/1893)
- Fix missing host in email links in local dev after Werkzeug 3.1.7+ bump ([#1894]https://github.com/ScilifelabDataCentre/dds_web/pull/1894)
- Added db-level UniqueConstraint on Files table to prevent duplicate (file, project_id) pairs ([#1890]https://github.com/ScilifelabDataCentre/dds_web/pull/1890)
11 changes: 9 additions & 2 deletions dds_web/api/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,23 @@ def post(self):

try:
db.session.commit()
Comment on lines 96 to 97

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.

An issue that arises with doing the IntegrityError check and rollback here, is that this "try" occurs after the file has already been uploaded to S3.

For example, locally I created a project and uploaded

first:

file1, file2, file3,

then:

file1, file2, file3, file4, file5.

In the second upload, I got Warning/Error for file1, file2, file3 and they were not added as duplicates to the db, however those files did get uploaded to S3. After these two operations I had:

Rows in "files": 5
Objects in the bucket: 8

This is of course better than having duplicates as well as orphaned objects as we would have without these changes, but maybe we can block the uploads to S3 as well?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, this is a fundamental problem with the way file uploads are done where the actual S3 upload is done by the client without any intervention from the backend and then the client contacts the backend about the database update. I really don't like it because, indeed, the client can in principle upload any old rubbish to the S3, and then when the db update fails, it's a pain to fix.
I guess a way to fix this might be to have the db update requested first, then the S3 upload...but then you will have problems when s3 uploads fail. I wondered if this should really be fixed by having the client push the files to a staging area on the backend and, having the backend push them to the actual S3 repository, so at least the backend has full control of what is going on.
So, in your example above, are the versions of file1, file2, file3 identical but with different names in the bucket, or what?

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 tried with identical files and differing files with the same name, in both cases they were added in the bucket with different names.

When uploading identical file1,2,3 and unique file2,4 these s3 objects are in the db:

58772bd698ba1d345ff3_6e72c8a0-0ed3-57a6-a67a-4205f8fad76492e3cdf4-4cc6-58e5-b452-eb46ef131bef
67a0b5d3afe7f5639e3c_6e72c8a0-0ed3-57a6-a67a-4205f8fad7641d75dbb1-febe-5ad2-a373-f75b129e76a0
9bf77fde82d52718a4e1_6e72c8a0-0ed3-57a6-a67a-4205f8fad764e9d0a2c0-4de5-5d19-a6f1-a9903913eaad
a07fbd62c98eaea2b8cb_6e72c8a0-0ed3-57a6-a67a-4205f8fad7640f9ab284-5ffa-56cb-b52f-db0b838408c5
e07fecddbd4d5f99dc97_6e72c8a0-0ed3-57a6-a67a-4205f8fad76470e0a422-1497-5535-9c47-0aeea60470d6

And these objects are in the s3 bucket:

58772bd698ba1d345ff3_6e72c8a0-0ed3-57a6-a67a-4205f8fad76492e3cdf4-4cc6-58e5-b452-eb46ef131bef
67a0b5d3afe7f5639e3c_6e72c8a0-0ed3-57a6-a67a-4205f8fad7641d75dbb1-febe-5ad2-a373-f75b129e76a0
9bf77fde82d52718a4e1_6e72c8a0-0ed3-57a6-a67a-4205f8fad764e9d0a2c0-4de5-5d19-a6f1-a9903913eaad
a07fbd62c98eaea2b8cb_6e72c8a0-0ed3-57a6-a67a-4205f8fad7640f9ab284-5ffa-56cb-b52f-db0b838408c5
b61113ce594be636c054_6e72c8a0-0ed3-57a6-a67a-4205f8fad7640f9ab284-5ffa-56cb-b52f-db0b838408c5
d732361d77633519c436_6e72c8a0-0ed3-57a6-a67a-4205f8fad76492e3cdf4-4cc6-58e5-b452-eb46ef131bef
d7acb66a36f8e0f73828_6e72c8a0-0ed3-57a6-a67a-4205f8fad7641d75dbb1-febe-5ad2-a373-f75b129e76a0
e07fecddbd4d5f99dc97_6e72c8a0-0ed3-57a6-a67a-4205f8fad76470e0a422-1497-5535-9c47-0aeea60470d6

Since the duplicate files' object names were so similar, I looked into it and the name comes from dds_cli file_handler_local at line 86:

new_name = f"{'%020x' % random.randrange(16**20)}_{uuid.uuid5(uuid.NAMESPACE_X500, str(folder))}{uuid.uuid5(uuid.NAMESPACE_X500, filename)}"

So I guess it's random + _ + folder + filename.

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.

Do you think we could just have the CLI delete the file it has just uploaded, if it is detected to have a duplicate filename?

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.

Alternatively maybe we could change it so that the filename is reserved but not committed at the start of an upload, so that other uploads fail immediately. Then commit it at the end only if it's successfully uploaded. But I think that would require too big of a change so probably out of scope.

except (sqlalchemy.exc.SQLAlchemyError, sqlalchemy.exc.OperationalError) as err:
except (
sqlalchemy.exc.SQLAlchemyError,
sqlalchemy.exc.OperationalError,
sqlalchemy.exc.IntegrityError,
Comment on lines -98 to +101

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.

IntegrityError is a subclass of SQLAlchemyError, so IntegrityErrors are already caught by the SQLAlchemyError class before adding IntegrityError to the tuple.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, I guess it is a bit pointless having them both in the tuple - I'll get rid of it

) as err:
flask.current_app.logger.debug(err)
db.session.rollback()
extra_message = ""
if isinstance(err, sqlalchemy.exc.IntegrityError):
extra_message = " - this file already uploaded to this project"
Comment on lines +106 to +107

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.

IntegrityError also covers for example broken foreign keys or missing required values among other things. We could possibly catch an IntegrityError here that is unrelated to duplicate file names, but we will then still print out " - this file already uploaded to this project".

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.

From what I can find there are no specific unique constraint errors, but it seems like we can find the error message from the db with err.origin.args according to this: https://stackoverflow.com/a/11662246

In which case we could parse the string for "Duplicate entry" or maybe just print that error string?

raise DatabaseError(
message=str(err),
alt_message="Failed to add new file to database"
+ (
": Database malfunction."
if isinstance(err, sqlalchemy.exc.OperationalError)
else "."
else f"{extra_message}."
Comment on lines 108 to +114

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.

The acceptance criteria in Jira are a bit confusing. They say this:

"NewFileSchema (or the calling resource) catches IntegrityError from this constraint specifically and surfaces it as FileExistsError.

Test that exercises the race: two threads submitting POST /file/new for the same (project_id, name) against a real test DB, asserting exactly one row ends up in files and the other request gets a clean 4xx."

So at the end there it says that we want a clean 4xx which is a client error, which makes sense. However we currently give 500. I guess it's also semantics if its a client error or a server error?

In dds_web/dds_web/errors.py we have a bunch of self defined errors. We could for example create a new custom one with "code = http.HTTPStatus.CONFLICT" which gives 409. But not sure if this is overkill/in line with the acceptance criteria or not.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Ah, yes, I was not following these criteria - I should write my own.
I have not tried to simulate an actual race condition - I could try to add one to the pytest suite I suppose.
I am not sure about what error should be returned - now the constraint exists, the actual error is a server error and it seems to me that as long as the error message tells the user what the problem is, it does not really matter.

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 forgot to mention tests but yea I think that would be a good test to add.

I also think it's fine to give 500, though I did think the output was a bit overwhelming to read when I uploaded several files that had duplicates. Every file gave a WARNING 3 times saying the filename exists with different wording:

image

),
) from err

Expand Down
5 changes: 4 additions & 1 deletion dds_web/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,10 @@ class File(db.Model):

# Table setup
__tablename__ = "files"
__table_args__ = {"extend_existing": True}
__table_args__ = (
db.UniqueConstraint("project_id", "name", name="ix_files_project_id_name"),
Comment thread
SevLG marked this conversation as resolved.
Resolved
{"extend_existing": True},
)

# Columns
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""files_unique_project_id_name

Revision ID: d50440766fc1
Revises: 0cd0a3b251e0
Create Date: 2026-11-05 12:33:27.088461

"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = "d50440766fc1"
down_revision = "0cd0a3b251e0"
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###

with op.batch_alter_table("files", schema=None) as batch_op:
batch_op.create_unique_constraint("ix_files_project_id_name", ["project_id", "name"])

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###

with op.batch_alter_table("files", schema=None) as batch_op:
batch_op.drop_constraint("ix_files_project_id_name", type_="unique")

# ### end Alembic commands ###
Loading