这是indexloc提供的服务,不要输入任何密码
Skip to content

chore: Benchmarks for ListObjects #2584

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from

Conversation

justincoh
Copy link
Contributor

@justincoh justincoh commented Jul 25, 2025

Description

What problem is being solved?

We don't currently have great benchmark coverage of ListObjects. We have an existing benchmark, but it doesn't distinguish between the various weights of relationships, and in the future our different optimization strategies will be based on the weight of the query being run.

How is it being solved?

This benchmark suite creates a single model with relations of weights 1, 2, 3, and INF. It then writes 10k tuples for each of those relationship weights and runs a specific assertion against each relation weight. It does the whole thing twice, once WithListObjectsOptimizationsEnabled(true) and once WithListObjectsOptimizationsEnabled(false).

Notes from local testing:

These benchmarks are run without a maxResults, and every case is designed to return 10k tuples; significantly more than the default ListObjects item return limit of 1k objects.


Summary

Weighted graph implementation is equal to or faster than non-weighted for all cases, and the weighted graph implementation uses significantly fewer resources in all cases.

  • For weight 1: the weighted graph implementation is significantly faster while also using significantly less memory
    • Direct weight one:
      • Speed: 3-4x faster
      • Memory usage reduced 70%,
      • Allocations reduced 80%
    • Computed weight one:
      • Speed 6-7x faster
      • Memory usage reduced 85%
      • Allocs reduced 90%
  • Weight 2:
    • Speed is the same
    • Memory usage reduced 70%
    • Allocs reduced 70%
  • Weight 3
    • Speed is the same
    • Memory reduced 70%
    • Allocs reduced 70%
  • Recursive:
    • Currently not supported by weighted graph implementation, coming soon.

Full results below, running with the same setup as our make test-bench. To reproduce run go test -bench BenchmarkListObjects ./pkg/server/commands/. -benchtime 5s -cpu 1 -benchmem -count 2

goos: darwin
goarch: arm64
pkg: github.com/openfga/openfga/pkg/server/commands
cpu: Apple M3 Max
BenchmarkListObjects/weight_one_direct_with_optimization         	     446	  13590323 ns/op	10006158 B/op	  154056 allocs/op
BenchmarkListObjects/weight_one_direct_with_optimization         	     436	  13541315 ns/op	10006506 B/op	  154058 allocs/op
BenchmarkListObjects/weight_one_direct_without_optimization      	     100	  50004680 ns/op	36308649 B/op	  747974 allocs/op
BenchmarkListObjects/weight_one_direct_without_optimization      	     121	  49517367 ns/op	36309010 B/op	  747977 allocs/op

BenchmarkListObjects/weight_one_computed_with_optimization       	     438	  13666988 ns/op	10008124 B/op	  154086 allocs/op
BenchmarkListObjects/weight_one_computed_with_optimization       	     440	  13688650 ns/op	10008328 B/op	  154088 allocs/op
BenchmarkListObjects/weight_one_computed_without_optimization    	      67	  85245305 ns/op	65024970 B/op	 1400994 allocs/op
BenchmarkListObjects/weight_one_computed_without_optimization    	      66	  85444212 ns/op	65025901 B/op	 1401000 allocs/op

BenchmarkListObjects/weight_two_ttu_with_optimizations           	       5	1030633025 ns/op	31139232 B/op	  666951 allocs/op
BenchmarkListObjects/weight_two_ttu_with_optimizations           	       5	1023868925 ns/op	31134816 B/op	  666923 allocs/op
BenchmarkListObjects/weight_two_ttu_without_optimizations        	       5	1160998225 ns/op	107275696 B/op	 2211035 allocs/op
BenchmarkListObjects/weight_two_ttu_without_optimizations        	       5	1158862258 ns/op	107266044 B/op	 2210973 allocs/op

BenchmarkListObjects/weight_three_with_optimization              	       3	2033734486 ns/op	49907552 B/op	 1139975 allocs/op
BenchmarkListObjects/weight_three_with_optimization              	       3	2029383972 ns/op	49909418 B/op	 1139986 allocs/op
BenchmarkListObjects/weight_three_without_optimization           	       3	2270150264 ns/op	181909744 B/op	 3784006 allocs/op
BenchmarkListObjects/weight_three_without_optimization           	       3	2297567167 ns/op	181916133 B/op	 3784042 allocs/op

BenchmarkListObjects/recursive_ttu_without_optimizations         	       4	1528705406 ns/op	74221072 B/op	 1549020 allocs/op
BenchmarkListObjects/recursive_ttu_without_optimizations         	       4	1577078438 ns/op	74223980 B/op	 1549049 allocs/op

Review Checklist

  • I have clicked on "allow edits by maintainers".
  • I have added documentation for new/changed functionality in this PR or in a PR to openfga.dev [Provide a link to any relevant PRs in the references section above]
  • The correct base branch is being used, if not main
  • I have added tests to validate that the change in functionality is working as expected

Summary by CodeRabbit

  • Tests
    • Added a comprehensive benchmark suite to evaluate the performance of listing objects with varying relationship complexities.
    • Introduced new helpers for efficiently setting up test data across different relationship types for benchmarking.

Copy link
Contributor

coderabbitai bot commented Jul 25, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A comprehensive benchmark suite was added to list_objects_test.go to measure the performance of the ListObjectsQuery.Execute method under various relationship complexities. Four helper functions were introduced to populate the datastore with different types of relationships. No existing code was modified; only new benchmarking and data setup logic was added.

Changes

File(s) Change Summary
pkg/server/commands/list_objects_test.go Added BenchmarkListObjects function and four helper functions for populating test data; no modifications to existing code.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/add-list-objects-benchmarks-1

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@justincoh justincoh changed the title messy but functional first benchmark chore: Benchmarks for ListObjects Jul 25, 2025
@justincoh justincoh added the Skip-Changelog Indicates that a PR does not need a changelog entry label Jul 25, 2025
Copy link

codecov bot commented Jul 25, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.42%. Comparing base (79a7630) to head (5641ea5).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2584      +/-   ##
==========================================
+ Coverage   90.39%   90.42%   +0.04%     
==========================================
  Files         140      140              
  Lines       19683    19683              
==========================================
+ Hits        17790    17796       +6     
+ Misses       1442     1438       -4     
+ Partials      451      449       -2     

☔ View full report in Codecov by Sentry.
📢 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.

@justincoh justincoh force-pushed the feat/add-list-objects-benchmarks-1 branch from 86487b2 to cb5e366 Compare July 25, 2025 17:42
@justincoh justincoh marked this pull request as ready for review July 25, 2025 19:35
@justincoh justincoh requested a review from a team as a code owner July 25, 2025 19:35
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ab5a75 and f667365.

📒 Files selected for processing (1)
  • pkg/server/commands/list_objects_test.go (3 hunks)
🧰 Additional context used
🪛 GitHub Actions: Pull Request
pkg/server/commands/list_objects_test.go

[error] 734-734: Benchmark test 'BenchmarkListObjects/weight_three_with_optimization' failed. See error trace at line 734.


[error] 743-743: Benchmark test 'BenchmarkListObjects/weight_three_without_optimization' failed. See error trace at line 743.

🔇 Additional comments (3)
pkg/server/commands/list_objects_test.go (3)

9-9: LGTM: Import additions are appropriate.

The new imports are necessary for the benchmark functionality:

  • ulid/v2 for unique ID generation
  • parser for DSL-to-proto transformation
  • tuple for creating TupleKey objects

Also applies to: 17-17, 29-29


583-641: Benchmark setup looks comprehensive and well-structured.

The setup correctly:

  • Creates an in-memory datastore with proper cleanup
  • Defines a realistic authorization model with different relationship weights
  • Uses ULIDs for unique identifiers
  • Sets up typesystem context and check resolver
  • Configures unlimited max results for consistent benchmarking

755-772: Good approach to handle unsupported recursive optimizations.

The commented-out recursive benchmark with optimizations is appropriate since the optimization currently falls back to non-optimized code. The TODO comment clearly indicates future work, and running only the non-optimized version provides a baseline for comparison.

Comment on lines +583 to +856
// b.Run("recursive_ttu_with_optimizations", func(b *testing.B) {
// query.optimizationsEnabled = true
// for i := 0; i < b.N; i++ {
// _, err := query.Execute(ctx, recursiveRequest)
// require.NoError(b, err)
// }
// })

b.Run("recursive_ttu_without_optimizations", func(b *testing.B) {
query.optimizationsEnabled = false
for i := 0; i < b.N; i++ {
res, err := query.Execute(ctx, recursiveRequest)
require.NoError(b, err)
require.Len(b, res.Objects, n)
}
})
}

// This helper writes tuples for user:justin with relation "member" to org:0...org:10000.
func createDirectWeightOneRelations(
b *testing.B,
ctx context.Context,
datastore storage.OpenFGADatastore,
storeID string,
numTuples int,
) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
obj := "org:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "member", "user:justin")
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}

func createWeightTwoRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
// These IDs can be the same as we already created org:0 - org:numTuples
obj := "company:" + strconv.Itoa(objID)
user := "org:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "owner", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}

func createWeightThreeRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
// These IDs can be the same as we already created org:0 - org:numTuples
obj := "office:" + strconv.Itoa(objID)
user := "company:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "parent", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}

func createRecursiveRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
// Every 10th item, make user:justin the leaf
if j%10 == 0 {
obj := "org:" + strconv.Itoa(objID)
tk := tuple.NewTupleKey(obj, "recursive", "user:justin")
tuples[j] = tk
tuples = append(tuples, tk)
objID++
continue
}

// otherwise, chain the org#parent#org relation
obj := "org:" + strconv.Itoa(objID)
user := "org:" + strconv.Itoa(objID-1)
tuples[j] = tuple.NewTupleKey(obj, "parent", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Excellent benchmark design with implementation issues to fix.

The benchmark suite design is comprehensive and valuable for performance testing:

Strengths:

  • Tests different relationship complexity weights (1, 2, 3, INF)
  • Compares optimized vs non-optimized implementations
  • Uses realistic authorization models
  • Proper benchmark patterns with setup/cleanup
  • Clear documentation and comments

Critical Issues:

  • Loop logic errors in all helper functions causing incorrect tuple counts
  • This explains the pipeline failures in weight_three benchmarks

Once the helper function fixes are applied, this will provide excellent benchmark coverage for ListObjects performance optimization work.

🧰 Tools
🪛 GitHub Actions: Pull Request

[error] 734-734: Benchmark test 'BenchmarkListObjects/weight_three_with_optimization' failed. See error trace at line 734.


[error] 743-743: Benchmark test 'BenchmarkListObjects/weight_three_without_optimization' failed. See error trace at line 743.

🤖 Prompt for AI Agents
In pkg/server/commands/list_objects_test.go from lines 583 to 856, the helper
functions creating tuples for the benchmark have loop logic errors causing
incorrect tuple counts and pipeline failures. To fix this, remove the increment
of objID inside the inner loop so that objID increments only once per outer loop
iteration. Also, ensure tuples slice is correctly sized and not appended to
inside the loop. This will correctly batch tuples per write and produce the
intended number of tuples for each benchmark weight.

Comment on lines +721 to +745
weightThreeRequest := &openfgav1.ListObjectsRequest{
StoreId: storeID,
AuthorizationModelId: model.GetId(),
Type: "office",
Relation: "weight_three",
User: "user:justin",
}

b.Run("weight_three_with_optimization", func(b *testing.B) {
query.optimizationsEnabled = true
for i := 0; i < b.N; i++ {
res, err := query.Execute(ctx, weightThreeRequest)
require.NoError(b, err)
require.Len(b, res.Objects, n)
}
})

b.Run("weight_three_without_optimization", func(b *testing.B) {
query.optimizationsEnabled = false
for i := 0; i < b.N; i++ {
res, err := query.Execute(ctx, weightThreeRequest)
require.NoError(b, err)
require.Len(b, res.Objects, n)
}
})
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Investigate weight_three benchmark failures.

The pipeline indicates these benchmarks are failing. This likely stems from issues in the createWeightThreeRelations helper function or the authorization model definition.

Based on pipeline failures, please verify the weight_three benchmark setup:


🏁 Script executed:

#!/bin/bash
# Verify the authorization model and tuple creation logic for weight_three relations

# Check the model definition for office type
ast-grep --pattern $'type office
  relations
    $$$'

# Look for any issues in createWeightThreeRelations function
ast-grep --pattern $'func createWeightThreeRelations($$$) {
  $$$
}'

Length of output: 1479


I wasn’t able to locate a “type office” definition in the test—only the helper that writes tuples for weight_three relations appeared. It looks like the authorization model for “office” never declares the “weight_three” relation (or “parent” at all), so the tuples you’re writing don’t match anything and the benchmark fails.

Please add or correct the type office { … relations { weight_three: user } } block in the model setup before invoking createWeightThreeRelations.

🧰 Tools
🪛 GitHub Actions: Pull Request

[error] 734-734: Benchmark test 'BenchmarkListObjects/weight_three_with_optimization' failed. See error trace at line 734.


[error] 743-743: Benchmark test 'BenchmarkListObjects/weight_three_without_optimization' failed. See error trace at line 743.

🤖 Prompt for AI Agents
In pkg/server/commands/list_objects_test.go around lines 721 to 745, the
benchmark test uses a "type office" with a "weight_three" relation, but the
authorization model setup lacks a definition for this type and relation. To fix
this, update the model setup to include a "type office" declaration with a
"weight_three: user" relation before calling createWeightThreeRelations,
ensuring the tuples written match the model and the benchmark runs correctly.

Comment on lines +775 to +795
// This helper writes tuples for user:justin with relation "member" to org:0...org:10000.
func createDirectWeightOneRelations(
b *testing.B,
ctx context.Context,
datastore storage.OpenFGADatastore,
storeID string,
numTuples int,
) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
obj := "org:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "member", "user:justin")
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical issue: Incorrect loop logic in tuple creation.

The nested loop structure has a fundamental flaw. The objID is incremented in both the outer loop condition and the inner loop body, causing:

  1. Fewer tuples to be created than expected
  2. Inconsistent object ID sequences
  3. Potential out-of-bounds conditions

Apply this fix to correct the loop logic:

-func createDirectWeightOneRelations(
-	b *testing.B,
-	ctx context.Context,
-	datastore storage.OpenFGADatastore,
-	storeID string,
-	numTuples int,
-) {
-	b.Helper()
-	for objID := 0; objID < numTuples; objID++ {
-		tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())
-
-		for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
-			obj := "org:" + strconv.Itoa(objID)
-			tuples[j] = tuple.NewTupleKey(obj, "member", "user:justin")
-			objID++
-		}
-		err := datastore.Write(ctx, storeID, nil, tuples)
-		require.NoError(b, err)
-	}
-}
+func createDirectWeightOneRelations(
+	b *testing.B,
+	ctx context.Context,
+	datastore storage.OpenFGADatastore,
+	storeID string,
+	numTuples int,
+) {
+	b.Helper()
+	objID := 0
+	for objID < numTuples {
+		batchSize := min(datastore.MaxTuplesPerWrite(), numTuples-objID)
+		tuples := make([]*openfgav1.TupleKey, batchSize)
+
+		for j := 0; j < batchSize; j++ {
+			obj := "org:" + strconv.Itoa(objID)
+			tuples[j] = tuple.NewTupleKey(obj, "member", "user:justin")
+			objID++
+		}
+		err := datastore.Write(ctx, storeID, nil, tuples)
+		require.NoError(b, err)
+	}
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In pkg/server/commands/list_objects_test.go around lines 775 to 795, the nested
loops incorrectly increment objID in both the outer and inner loops, leading to
fewer tuples and inconsistent object IDs. Fix this by removing the objID
increment from the inner loop and only incrementing it in the outer loop,
ensuring the correct number of tuples are created with sequential object IDs.

Comment on lines +797 to +812
func createWeightTwoRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
// These IDs can be the same as we already created org:0 - org:numTuples
obj := "company:" + strconv.Itoa(objID)
user := "org:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "owner", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Same loop logic issue as previous helper function.

This function has the identical nested loop problem with objID being incremented incorrectly.

Apply the same fix pattern:

-func createWeightTwoRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
-	b.Helper()
-	for objID := 0; objID < numTuples; objID++ {
-		tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())
-
-		for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
-			// These IDs can be the same as we already created org:0 - org:numTuples
-			obj := "company:" + strconv.Itoa(objID)
-			user := "org:" + strconv.Itoa(objID)
-			tuples[j] = tuple.NewTupleKey(obj, "owner", user)
-			objID++
-		}
-		err := datastore.Write(ctx, storeID, nil, tuples)
-		require.NoError(b, err)
-	}
-}
+func createWeightTwoRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
+	b.Helper()
+	objID := 0
+	for objID < numTuples {
+		batchSize := min(datastore.MaxTuplesPerWrite(), numTuples-objID)
+		tuples := make([]*openfgav1.TupleKey, batchSize)
+
+		for j := 0; j < batchSize; j++ {
+			obj := "company:" + strconv.Itoa(objID)
+			user := "org:" + strconv.Itoa(objID)
+			tuples[j] = tuple.NewTupleKey(obj, "owner", user)
+			objID++
+		}
+		err := datastore.Write(ctx, storeID, nil, tuples)
+		require.NoError(b, err)
+	}
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func createWeightTwoRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())
for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
// These IDs can be the same as we already created org:0 - org:numTuples
obj := "company:" + strconv.Itoa(objID)
user := "org:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "owner", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}
func createWeightTwoRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
objID := 0
for objID < numTuples {
batchSize := min(datastore.MaxTuplesPerWrite(), numTuples-objID)
tuples := make([]*openfgav1.TupleKey, batchSize)
for j := 0; j < batchSize; j++ {
obj := "company:" + strconv.Itoa(objID)
user := "org:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "owner", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}
🤖 Prompt for AI Agents
In pkg/server/commands/list_objects_test.go around lines 797 to 812, the nested
loop incorrectly increments objID inside the inner loop, causing it to skip
values and misalign tuple creation. To fix this, remove the objID++ increment
from inside the inner loop and instead increment objID only once per outer loop
iteration, ensuring each objID is used correctly for tuple creation.

Comment on lines +814 to +829
func createWeightThreeRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
// These IDs can be the same as we already created org:0 - org:numTuples
obj := "office:" + strconv.Itoa(objID)
user := "company:" + strconv.Itoa(objID)
tuples[j] = tuple.NewTupleKey(obj, "parent", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Root cause of pipeline failures: Incorrect loop logic.

This function contains the same loop logic error that's causing the weight_three benchmark failures. The incorrect objID incrementing means fewer than 10,000 tuples are created, causing the require.Len(b, res.Objects, n) assertions to fail.

Apply the corrected loop logic:

-func createWeightThreeRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
-	b.Helper()
-	for objID := 0; objID < numTuples; objID++ {
-		tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())
-
-		for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
-			// These IDs can be the same as we already created org:0 - org:numTuples
-			obj := "office:" + strconv.Itoa(objID)
-			user := "company:" + strconv.Itoa(objID)
-			tuples[j] = tuple.NewTupleKey(obj, "parent", user)
-			objID++
-		}
-		err := datastore.Write(ctx, storeID, nil, tuples)
-		require.NoError(b, err)
-	}
-}
+func createWeightThreeRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
+	b.Helper()
+	objID := 0
+	for objID < numTuples {
+		batchSize := min(datastore.MaxTuplesPerWrite(), numTuples-objID)
+		tuples := make([]*openfgav1.TupleKey, batchSize)
+
+		for j := 0; j < batchSize; j++ {
+			obj := "office:" + strconv.Itoa(objID)
+			user := "company:" + strconv.Itoa(objID)
+			tuples[j] = tuple.NewTupleKey(obj, "parent", user)
+			objID++
+		}
+		err := datastore.Write(ctx, storeID, nil, tuples)
+		require.NoError(b, err)
+	}
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In pkg/server/commands/list_objects_test.go around lines 814 to 829, the
function createWeightThreeRelations incorrectly increments objID inside the
inner loop, causing fewer tuples than expected to be created. To fix this,
remove the objID++ increment from inside the inner loop and instead increment
objID only in the outer loop, ensuring the correct total number of tuples are
generated and the benchmark assertions pass.

Comment on lines +831 to +856
func createRecursiveRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
b.Helper()
for objID := 0; objID < numTuples; objID++ {
tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())

for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
// Every 10th item, make user:justin the leaf
if j%10 == 0 {
obj := "org:" + strconv.Itoa(objID)
tk := tuple.NewTupleKey(obj, "recursive", "user:justin")
tuples[j] = tk
tuples = append(tuples, tk)
objID++
continue
}

// otherwise, chain the org#parent#org relation
obj := "org:" + strconv.Itoa(objID)
user := "org:" + strconv.Itoa(objID-1)
tuples[j] = tuple.NewTupleKey(obj, "parent", user)
objID++
}
err := datastore.Write(ctx, storeID, nil, tuples)
require.NoError(b, err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Multiple critical issues in recursive relations helper.

This function has several problems:

  1. Same loop logic issue as other helpers with incorrect objID incrementing
  2. Slice capacity violation: Line 842 appends to a slice already at MaxTuplesPerWrite() capacity
  3. Logic error: The continue on line 844 skips the inner loop increment, causing index misalignment

Apply this comprehensive fix:

-func createRecursiveRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
-	b.Helper()
-	for objID := 0; objID < numTuples; objID++ {
-		tuples := make([]*openfgav1.TupleKey, datastore.MaxTuplesPerWrite())
-
-		for j := 0; j < datastore.MaxTuplesPerWrite(); j++ {
-			// Every 10th item, make user:justin the leaf
-			if j%10 == 0 {
-				obj := "org:" + strconv.Itoa(objID)
-				tk := tuple.NewTupleKey(obj, "recursive", "user:justin")
-				tuples[j] = tk
-				tuples = append(tuples, tk)
-				objID++
-				continue
-			}
-
-			// otherwise, chain the org#parent#org relation
-			obj := "org:" + strconv.Itoa(objID)
-			user := "org:" + strconv.Itoa(objID-1)
-			tuples[j] = tuple.NewTupleKey(obj, "parent", user)
-			objID++
-		}
-		err := datastore.Write(ctx, storeID, nil, tuples)
-		require.NoError(b, err)
-	}
-}
+func createRecursiveRelations(b *testing.B, ctx context.Context, datastore storage.OpenFGADatastore, storeID string, numTuples int) {
+	b.Helper()
+	objID := 0
+	for objID < numTuples {
+		batchSize := min(datastore.MaxTuplesPerWrite(), numTuples-objID)
+		tuples := make([]*openfgav1.TupleKey, 0, batchSize)
+
+		for j := 0; j < batchSize && objID < numTuples; j++ {
+			// Every 10th item, make user:justin the leaf
+			if objID%10 == 0 {
+				obj := "org:" + strconv.Itoa(objID)
+				tk := tuple.NewTupleKey(obj, "recursive", "user:justin")
+				tuples = append(tuples, tk)
+			} else {
+				// otherwise, chain the org#parent#org relation
+				obj := "org:" + strconv.Itoa(objID)
+				user := "org:" + strconv.Itoa(objID-1)
+				tuples = append(tuples, tuple.NewTupleKey(obj, "parent", user))
+			}
+			objID++
+		}
+		err := datastore.Write(ctx, storeID, nil, tuples)
+		require.NoError(b, err)
+	}
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In pkg/server/commands/list_objects_test.go lines 831 to 856, the
createRecursiveRelations function incorrectly increments objID inside the inner
loop causing logic errors, appends to a slice already at max capacity causing
slice capacity violation, and uses continue which skips necessary increments
leading to index misalignment. To fix, remove the append operation to the tuples
slice to avoid capacity overflow, adjust objID increments to happen only once
per iteration in a controlled manner, and replace continue with proper
conditional logic to ensure all loop indices and increments align correctly
without skipping steps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Skip-Changelog Indicates that a PR does not need a changelog entry
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant