Skip to content

added new constraint on Files table - #1890

Open
jimdale wants to merge 7 commits into
devfrom
fix/filename_project_id_constraint
Open

jimdale wants to merge 7 commits into
devfrom
fix/filename_project_id_constraint

Conversation

@jimdale

@jimdale jimdale commented Nov 6, 2026 •

Copy link
Copy Markdown

Pull Request Template

Before Marking as Ready for Review

  • Add relevant information to the sections below (Summary etc)
  • Rebase or merge the latest dev (or other targeted branch)
  • Update documentation if needed
  • Add an entry to the SPRINTLOG.md if needed
  • Choose an appropriate label. See here for information on the labelling options
  • The code follows the style guidelines
  • Perform a self-review: read the diff as if reviewing someone else's code
  • I have commented the code, particularly in hard-to-understand areas
  • Verify that all checks and tests have passed

If the target branch is master:

Summary

Attempts to fix an issue whereby there is no database-level constriant preventing the creation of identical (project_id, filename) pairs.
In principal this can be fixed by executing directly on the db

ALTER TABLE files ADD UNIQUE ix_files_name_project_id(project_id, name(255));

which creates a prefix index on the first 255 characters of name, and a composite index searchable via a BTREE.
The alternative

ALTER TABLE files ADD UNIQUE ix_files_name_project_id(project_id, name);

uses the whole of the name column, and creates a HASH index.

In reality, changes must go through flask-sqlalchemy/Alembic. Once can add a UniqueConstraint object to the table_args parameter of a table, but it only seems to be possible to reproduce the second example above, with the HASH index.

I proceeded to create an Alembic migration imposing a constraint using a joint HASH index on (name, project_id)

Related Issue/Ticket

https://scilifelab.atlassian.net/jira/software/projects/HMS/boards/13/backlog?selectedIssue=HMS-2657

Testing

This has been tested by first confirming with a db query that the constraint has been created:

SHOW INDEXES FROM files;

confirms that the constraint has been created.
To test that it works, the application-level checks preventing duplicate (name, project_id) pairs need to be disabled.

On the CLIENT:

in the /file_handler_local/LocalFileHander.check_previous_upload method, at the end of the method, change to read

    LOG.debug("Previous upload check finished.")

    files_in_db["files"] = None ## temporarily disable check

    return {} if files_in_db["files"] is None else files_in_db["files"] 

On the BACKEND:

At the end of /schemas/file_schemas.verify_file_not_exists, change to read

    file = None ## temporarily disable check

    if file:
        raise FileExistsError

If you now upload the same file to the same project twice, the client should now raise an error of the form

WARNING  Failed to add file 'xxxxxx' to database: Failed to add new file to database - this file already uploaded to  this project.   

Reviewer Notes

See above regarding tests conducted.


Once all boxes are checked, mark the PR as Ready for Review and tag at least one team member as the initial reviewer.

@jimdale
jimdale requested a review from a team as a code owner November 6, 2026 14:15
@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 92.92%. Comparing base (da7ac68) to head (1fbb135).

Files with missing lines Patch % Lines
dds_web/api/files.py 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev    #1890      +/-   ##
==========================================
- Coverage   92.94%   92.92%   -0.02%     
==========================================
  Files          30       30              
  Lines        5074     5077       +3     
==========================================
+ Hits         4716     4718       +2     
- Misses        358      359       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@valyo
valyo marked this pull request as draft November 9, 2026 10:37
@jimdale
jimdale marked this pull request as ready for review November 18, 2026 09:06
Comment thread dds_web/api/files.py
Comment on lines -98 to +101
except (sqlalchemy.exc.SQLAlchemyError, sqlalchemy.exc.OperationalError) as err:
except (
sqlalchemy.exc.SQLAlchemyError,
sqlalchemy.exc.OperationalError,
sqlalchemy.exc.IntegrityError,

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

Comment thread dds_web/api/files.py
Comment on lines +106 to +107
if isinstance(err, sqlalchemy.exc.IntegrityError):
extra_message = " - 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.

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?

Comment thread dds_web/api/files.py
Comment on lines 108 to +114
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}."

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

@SevLG SevLG 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.

Looks good so far, added some comments above.

What I tested:

  • Built current dev branch and tried uploading duplicate file names, blocked by verify_file_not_exists.
  • Added file = None and files_in_db["files"] = None as described in PR description and tried again, was able to upload duplicates that were added in db.
  • Built from this branch, added file = None and files_in_db["files"] = None and tried again, got error messages for each duplicate file name and the file names were not added to db.

@SevLG SevLG 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.

Another thing from the acceptance criteria:

"Migration is idempotent and dedupes pre-existing duplicates if any are found, with a clear log of which rows it removed."

This hasn't been adressed in this PR I think? It seems like it could be a lot of work for something that will presumably only happen one time. Possibly we could work around it by going through and cleaning out the db manually and logging them before applying?

Comment thread dds_web/api/files.py
Comment on lines 96 to 97
try:
db.session.commit()

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.

Comment thread dds_web/database/models.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants