Skip to content

feat(policy): add sort ListSubjectMappings API#3255

Draft
dsm20 wants to merge 7 commits intomainfrom
feat/DSPX-2685-add-sort-listsubjectmappings
Draft

feat(policy): add sort ListSubjectMappings API#3255
dsm20 wants to merge 7 commits intomainfrom
feat/DSPX-2685-add-sort-listsubjectmappings

Conversation

@dsm20
Copy link
Copy Markdown
Contributor

@dsm20 dsm20 commented Apr 2, 2026

Proposed Changes

Protoservice/policy/subjectmapping/subject_mapping.proto

  • SortSubjectMappingsType enum (UNSPECIFIED, CREATED_AT, UPDATED_AT)
  • SubjectMappingsSort message (field + direction)
  • repeated SubjectMappingsSort sort = 11 on ListSubjectMappingsRequest with max_items = 1 constraint
  • Regenerated protos and docs

SQLservice/policy/db/queries/subject_mappings.sql

  • CASE WHEN ORDER BY blocks for created_at and updated_at (ASC/DESC each)
  • Fallback sm.created_at DESC + tiebreaker sm.id ASC

Goservice/policy/db/utils.go + service/policy/db/subject_mappings.go

  • GetSubjectMappingsSortParams(): maps enum to SQL-compatible field/direction strings
  • ListSubjectMappings handler wired to call mapper and pass params to sqlc query

Tests

  • 9 unit tests for the enum mapper helper (nil, empty, unspecified, each field + direction)
  • 5 integration tests (created_at ASC/DESC, updated_at ASC/DESC, unspecified fallback)

Notes

Checklist

  • I have added or updated unit tests
  • I have added or updated integration tests (if appropriate)
  • I have added or updated documentation

Testing Instructions

Summary by CodeRabbit

Release Notes

  • New Features
    • Added sorting support for subject mappings list operations, enabling sort by creation date or update date in ascending or descending order.

dsm20 added 7 commits April 2, 2026 13:05
define SortSubjectMappingsType enum and SubjectMappingsSort message for strongly-typed sort on ListSubjectMappings RPC
following the pattern, change the ORDER BY to incorporate CASE WHEN structuring with the sort fields
helper maps proto enum values to strings, handler passes strings to sqlc
implement unit tests for all sort functions including nil, empty slice, nill element ([nill])
added 5 integration tests: CreatedAt ASC/DESC, UpdatedAt ASC/DESC, and then FallsBackToDefault (CreatedAt DESC)
ran buf generate originally, but needed to do 'make proto-generate' to capture grpc and openai docs
@dsm20 dsm20 requested review from a team as code owners April 2, 2026 17:38
@dsm20 dsm20 marked this pull request as draft April 2, 2026 17:38
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 2, 2026

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(policy): add sort ListSubjectMappings API' directly summarizes the main change: adding sorting capability to the ListSubjectMappings API.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/DSPX-2685-add-sort-listsubjectmappings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added comp:db DB component comp:policy Policy Configuration ( attributes, subject mappings, resource mappings, kas registry) docs Documentation labels Apr 2, 2026
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces sorting capabilities to the ListSubjectMappings API. It defines the necessary protocol buffer structures, implements the mapping logic in the Go service layer, and updates the underlying SQL queries to handle dynamic sorting parameters. The changes ensure that API consumers can sort results by creation or update timestamps while maintaining backward compatibility.

Highlights

  • API Enhancement: Added support for sorting in the ListSubjectMappings API by introducing a new SortSubjectMappingsType enum and SubjectMappingsSort message.
  • Database Updates: Updated the SQL query to support dynamic sorting by created_at or updated_at fields, with a fallback to default ordering.
  • Testing: Added comprehensive unit tests for the sorting parameter mapper and integration tests to verify sorting behavior for both created_at and updated_at fields.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Ignored Files
  • Ignored by pattern: docs/openapi/**/* (2)
    • docs/openapi/authorization/authorization.openapi.yaml
    • docs/openapi/policy/subjectmapping/subject_mapping.openapi.yaml
  • Ignored by pattern: protocol/**/* (1)
    • protocol/go/policy/subjectmapping/subject_mapping.pb.go
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.


The list was static, fixed in time, Now sorting makes it feel sublime. By date or update, order flows, As logic in the database grows.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions github-actions bot added the size/m label Apr 2, 2026
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces sorting capabilities for listing subject mappings, allowing users to sort by creation and update timestamps in both ascending and descending order. The changes include updates to the protobuf definitions, database queries, and utility functions, supported by comprehensive integration and unit tests. Review feedback highlights opportunities to reduce code duplication in the new integration tests by extracting a helper method for subject mapping creation and to simplify a switch statement within the sorting utility function.

Comment on lines +604 to +632
createMapping := func(email string) string {
scs := &subjectmapping.SubjectConditionSetCreate{
SubjectSets: []*policy.SubjectSet{
{
ConditionGroups: []*policy.ConditionGroup{
{
BooleanOperator: policy.ConditionBooleanTypeEnum_CONDITION_BOOLEAN_TYPE_ENUM_AND,
Conditions: []*policy.Condition{
{
SubjectExternalSelectorValue: ".email",
Operator: policy.SubjectMappingOperatorEnum_SUBJECT_MAPPING_OPERATOR_ENUM_IN,
SubjectExternalValues: []string{email},
},
},
},
},
},
},
}

created, err := s.db.PolicyClient.CreateSubjectMapping(s.ctx, &subjectmapping.CreateSubjectMappingRequest{
AttributeValueId: fixtureAttrValID,
NewSubjectConditionSet: scs,
Actions: []*policy.Action{actionRead},
})
s.Require().NoError(err)
s.Require().NotEmpty(created.GetId())
return created.GetId()
}
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.

medium

There's significant code duplication across the new test functions (Test_ListSubjectMappings_SortByCreatedAt_ASC, Test_ListSubjectMappings_SortByCreatedAt_DESC, etc.). The createMapping local function and its setup variables are identical in all of them.

To improve maintainability and reduce redundancy, consider extracting this logic into a helper method on the SubjectMappingsSuite struct. This will make the tests cleaner and easier to manage.

For example:

func (s *SubjectMappingsSuite) createMappingForSortTest(email string) string {
    fixtureAttrValID := s.f.GetAttributeValueKey("example.net/attr/attr1/value/value2").ID
    actionRead := s.f.GetStandardAction(policydb.ActionRead.String())

    scs := &subjectmapping.SubjectConditionSetCreate{
        SubjectSets: []*policy.SubjectSet{
            {
                ConditionGroups: []*policy.ConditionGroup{
                    {
                        BooleanOperator: policy.ConditionBooleanTypeEnum_CONDITION_BOOLEAN_TYPE_ENUM_AND,
                        Conditions: []*policy.Condition{
                            {
                                SubjectExternalSelectorValue: ".email",
                                Operator:                     policy.SubjectMappingOperatorEnum_SUBJECT_MAPPING_OPERATOR_ENUM_IN,
                                SubjectExternalValues:        []string{email},
                            },
                        },
                    },
                },
            },
        },
    }

    created, err := s.db.PolicyClient.CreateSubjectMapping(s.ctx, &subjectmapping.CreateSubjectMappingRequest{
        AttributeValueId:       fixtureAttrValID,
        NewSubjectConditionSet: scs,
        Actions:                []*policy.Action{actionRead},
    })
    s.Require().NoError(err)
    s.Require().NotEmpty(created.GetId())
    return created.GetId()
}

Then, each test can simply call s.createMappingForSortTest(...).

Comment on lines +292 to +301
switch s.GetField() {
case subjectmapping.SortSubjectMappingsType_SORT_SUBJECT_MAPPINGS_TYPE_CREATED_AT:
field = "created_at"
case subjectmapping.SortSubjectMappingsType_SORT_SUBJECT_MAPPINGS_TYPE_UPDATED_AT:
field = "updated_at"
case subjectmapping.SortSubjectMappingsType_SORT_SUBJECT_MAPPINGS_TYPE_UNSPECIFIED:
return "", ""
default:
return "", ""
}
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.

medium

The switch statement can be simplified. The case for UNSPECIFIED and the default case have identical logic. You can remove the UNSPECIFIED case entirely and let default handle it, making the code more concise.

	switch s.GetField() {
	case subjectmapping.SortSubjectMappingsType_SORT_SUBJECT_MAPPINGS_TYPE_CREATED_AT:
		field = "created_at"
	case subjectmapping.SortSubjectMappingsType_SORT_SUBJECT_MAPPINGS_TYPE_UPDATED_AT:
		field = "updated_at"
	default:
		return "", ""
	}

Copy link
Copy Markdown
Contributor Author

@dsm20 dsm20 Apr 2, 2026

Choose a reason for hiding this comment

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

@gemini-code-assist this pattern of including both UNSPECIFIED and default is already established and serves more to document the fact that UNSPECIFIED is being recognized/accounted for, and the default is there just as a safety. Same returns.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 2, 2026

Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 202.048429ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 98.477362ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 390.201096ms
Throughput 256.28 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 40.765670014s
Average Latency 406.077835ms
Throughput 122.65 requests/second

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 2, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:db DB component comp:policy Policy Configuration ( attributes, subject mappings, resource mappings, kas registry) docs Documentation size/m

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant