aws-sdk-net: 'DynamoDbContext.LoadAsync' does not respect 'DynamoDBOperationConfig.IndexName'

Description

When using the LoadAsync method on IDynamoDbContext to load an entity using a secondary global index, I’m getting unexpected behavior: an InvalidCastException is being thrown.

Switching the exact same call to a QueryAsync fixes the problem.

I believe LoadAsync is not respecting the IndexName property on the configuration object and is using the primary index for all searches. Either the API is incredibly misleading (as it allows you to pass this unused value) or there is a bug there.

Reproduction Steps

  1. Create a table with a primary and a secondary index
  2. Map the primary key to a Guid property
  3. Map the secondary key to a string property
    [DynamoDBTable("Somethings")]
    internal sealed class Something
    {
        [DynamoDBHashKey]
        public Guid? Id { get; set; }

        [DynamoDBGlobalSecondaryIndexHashKey]
        public string? Name { get; set; }
    }
  1. Try to use LoadAsync with a string key and pass new DynamoDBOperationConfig { IndexName = <Name_Of_Secondary_Index> } as options
await dynamoDBContext.LoadAsync<Something>("someName", new DynamoDBOperationConfig { IndexName = "Name-index" });
  1. An InvalidCastException is thrown
  2. Replace the LoadAsync call with QueryAsync, and it works as expected:
var query = dynamoDBContext.QueryAsync<Something>("someName", new DynamoDBOperationConfig { IndexName = "Name-index" });
await query.GetNextSetAsync();

Logs

System.InvalidCastException: Unable to cast object of type ‘System.String’ to type ‘System.Guid’. at Amazon.DynamoDBv2.Converter`1.TryTo(Object value, Primitive& p) at Amazon.DynamoDBv2.Converter.TryToEntry(Object value, DynamoDBEntry& entry) at Amazon.DynamoDBv2.Converter.ToEntry(Object value) at Amazon.DynamoDBv2.DynamoDBEntryConversion.ConvertToEntry(Type inputType, Object value) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.ToDynamoDBEntry(SimplePropertyStorage propertyStorage, Object value, DynamoDBFlatConfig flatConfig, Boolean canReturnScalarInsteadOfList) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.ToDynamoDBEntry(SimplePropertyStorage propertyStorage, Object value, DynamoDBFlatConfig flatConfig) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.ValueToDynamoDBEntry(PropertyStorage propertyStorage, Object value, DynamoDBFlatConfig flatConfig) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.MakeKey(Object hashKey, Object rangeKey, ItemStorageConfig storageConfig, DynamoDBFlatConfig flatConfig) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.LoadHelperAsync[T](Object hashKey, Object rangeKey, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken) at Amazon.DynamoDBv2.DataModel.DynamoDBContext.LoadAsync[T](Object hashKey, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken)

Environment

  • SDK Version: AWSSDK.Core Version=“3.5.1.39”
  • Package Version: AWSSDK.DynamoDBv2 Version=“3.5.3.3”
  • OS Info: Windows 10
  • Build Environment Visual Studio 2019 16.8.1
  • Targeted .NET Platform: Net Core 3.1

Resolution

  • 👋 I can/would-like-to implement a fix for this problem myself

I belive LoadAsync should be changed to respect the index being passed as a parameter and use the object hashKey against that.


This is a 🐛 bug-report

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 23 (10 by maintainers)

Most upvoted comments

Just spent a day banging my head into the wall trying to LoadAsync() from a GSI having only a hash (but no sort) key which means there must be exactly one result matching the key. Having to use QueryAsync().GetRemainingAsync().Single() in such case is not very intuitive.

The LoadAsync is part of DynamoDB Object Persistence model (similar to ORM frameworks for relational databases). For the mentioned problem, you have used Guild at C# object level instead of string at DynamoDb level.

Incorrect. The problem I’m having is not with the primary key (which is mapped as Guid in C# code) but with the hash key for the secondary index, which is string on both ends.

DynamoDB Object Persistence model can map arbitrary data types to DynamoDB properties via type converters.

I understand that, however the Guid primary key is working fine for me without having to create any converters. I think you should probably update your documentation to clarify the behavior around Guids in the Object Persistence Model, since they appear supported even though they are not listed there.

Also notice that first parameter of LoadAsync is of type object. Hence before executing the query, it tries to map the object type value to proper object (Something) property type (Guid) value.

I understand the error, but I don’t understand why it is attempting to perform that conversion in the first place. The type it should be attempting to cast to for the secondary index is string, not Guid: I’m not performing an operation on the primary index here when specifying IndexName.

For the 2nd question, DynamoDB SDK’s LoadAsync method calls GetItem service API operation. If you refer Service API reference for GetItem, it expects Key request parameter which is a A map of attribute names to AttributeValue objects, representing the primary key of the item to retrieve.

Now this is where it gets incredibly misleading then. The LoadAsync API names the first parameter hashKey, not primaryKey. Following that nomenclature, one would understand it is “the hashkey for the index being searched”, since:

  • you can specify the index name as an additional parameter
  • every index in DynamoDB has its own hashKey

If it truly is referring to the primary hashkey, then the API is incredibly misleading an needs work, in my opinion. Especially when directly compared to “sibling” APIs like QueryAsync, which takes the same parameters, but actually works on the index you specify and not only on the primary index.

I’m not sure if for your use case (per your 2nd question), you intend to use Query operation.

From the API surface, it would appear that LoadAsync should work on my scenario, but it doesn’t. As I mentioned in the OP, I think either the API should be changed to support the scenario, or it should prohibit you from passing an index name into the method. The former is preferred in my view for API consistency (working similarly to QueryAsync).

We’ve merged #3421 into the v4-development branch, which includes a new set of operation-specific config objects LoadConfig, SaveConfig, QueryConfig, etc. This should help avoid confusion about IndexName and other properties that only apply to a subset of operations moving forward.

We’ve marked the methods that take DynamoDBOperationConfig as deprecated in V4, but are not planning to remove them entirely yet. We may do so in a future major version.

We’re still working on getting preview packages published, you can track overall V4 progress in #3362. We’ll leave this issue open until at least V4 hits GA.

The V4 preview is out, please let us know if you find any issues with the new operation-specific config objects.

For the short term, we’ve clarified the Load/LoadAsync documentation starting in DynamoDBv2 v3.7.303.9 via #3320 to explain that 1) it calls GetItem under the hood, which relies on the primary key and 2) IndexName on the config does not influence which item is loaded.

Longer term, we would like to make the change @julealgon suggested above - move away from the “shared” DynamoDBOperationConfig towards operation-specific configs that only contain applicable settings for each. You may have noticed the v4-development branch, this is on our list of desired DynamoDB changes along with the interface/mockability issues.

Wow, I just spent hours trying to work out what I was doing wrong! This really needs to be included in the documentation if it’s not going to be fixed. It would’ve saved me so much headache!

Needs review on how we could implement this documentation change.

Thank you @normj for the information.

At this point changing this would be a serious breaking change which we are not ready to make. At this point the best we can do is improve the documentation. Anything else causes serious breaking changes.

If you are not willing to change the behavior of the API, perhaps you could introduce new overloads, with a tighter config model (containing only the settings that make sense for any given operation) while retaining the old overload as-is, but marking it as deprecated. That would allow you to slowly phase it out and replace with the newer, more robust one.

Another potential option would be to actually throw an exception at runtime when an invalid setting is passed into the call. I’d rather get an exception that tells me why that setting cannot be used, than get “wrong results” as is happening right now.

Anyways, very unfortunate to have such a misleading API stuck in place. I’ll probably need a significant comment block in my code to explain this anomaly and justify using the Query syntax in my repository implementation. I hope you can look back at this at some point and rethink the strategy (maybe implement an EF provider instead of a custom model, like CosmosDB does and some paid providers provide). Clearly, the “wheel reimplementation” here created unnecessary problems for consumers.