Skip to content
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

chore(fix): supabase adapter #2258

Open
wants to merge 40 commits into
base: develop
Choose a base branch
from

Conversation

antman1p
Copy link
Contributor

Relates to

This PR does not relate to a specific issue but introduces multiple enhancements and optimizations to the Supabase database adapter.

Risks

Risk Level: Low

Potential Impact:

  • Changes primarily focus on query optimizations and error handling improvements.
  • Possible risks include unexpected query behavior or edge cases not previously encountered.
  • Requires verification that caching, memory queries, and relationship management work as expected.

Background

What does this PR do?

This PR introduces several improvements and optimizations to the SupabaseDatabaseAdapter in packages/adapter-supabase/src/index.ts. The key changes include:

  • Enhanced Error Handling: Improved logging and structured error messages for better debugging.
  • Query Optimization: Refactored how memory tables are queried dynamically based on embedding size.
  • More Robust getMemoryById Implementation: Now iterates through potential memory tables instead of assuming a single table.
  • Ensuring Unique Entries in Relationships: Improved relationship handling by checking for existing rooms before creating new ones.
  • More Efficient Memory Creation: Includes validation for embedding sizes and converts timestamps properly.
  • Caching for Knowledge Search: Implements a caching mechanism to improve performance.
  • Better Handling of maybeSingle(): Uses maybeSingle() in cases where a single record is expected, avoiding unnecessary errors.

What kind of change is this?

  • Improvements: Various optimizations and refactoring of existing logic.
  • Bug Fixes: Ensuring better error handling and database query robustness.
  • Features: Adds caching and improves relationship consistency management.

Documentation changes needed?

  • My changes do not require a change to the project documentation.

Testing

Where should a reviewer start?

  1. Review SupabaseDatabaseAdapter.ts in packages/adapter-supabase/src/index.ts.
  2. Check changes to getMemoryById, createMemory, getRoomsForParticipants, and searchKnowledge methods.
  3. Verify SQL queries have been optimized (dynamic memory table selection, better relationship checks, etc.).

Detailed testing steps

  1. Run automated tests to verify that the database queries execute correctly.
  2. Manually test the caching logic by searching knowledge (searchKnowledge()) and checking if cache retrieval works.
  3. Check new logging improvements by inducing intentional errors (e.g., incorrect queries) and confirming structured error messages.
  4. Verify memory creation for various embedding sizes (384, 768, 1024, 1536).
  5. Confirm room creation logic properly reuses existing rooms between users rather than duplicating them.

Deploy Notes

  • You must run the schema.sql file in the supabase SQL editor. You will also need to add the functions to supabase via the SQL editor. I have the functions in my dump file. I will need to add them to the schema.sql file.

Database changes

  • No schema changes, but queries have been optimized to select the appropriate memory tables dynamically.

Deployment instructions

  • Standard deployment process.
  • Ensure all database queries are tested before merging.

Discord username

4n7m4n

- **Enhanced Error Handling**: Improved logging and structured error messages for better debugging.
- **Query Optimization**: Refactored how memory tables are queried dynamically based on embedding size.
- **More Robust `getMemoryById` Implementation**: Now iterates through potential memory tables instead of assuming a single table.
- **Ensuring Unique Entries in Relationships**: Improved relationship handling by checking for existing rooms before creating new ones.
- **More Efficient Memory Creation**: Includes validation for embedding sizes and converts timestamps properly.
- **Caching for Knowledge Search**: Implements a caching mechanism to improve performance.
- **Better Handling of `maybeSingle()`**: Uses `maybeSingle()` in cases where a single record is expected, avoiding unnecessary errors.
Added functions that need to be pasted into supabase SQL editor along with this entire schema to create the db for Eliza.
@RobertDoc
Copy link

Tried this PR as Supabase is broken on the latest tag and develop:

Error: Error creating room: Could not find the function public.create_room(roomId) in the schema cache

Looks like we're still missing some functions

@antman1p
Copy link
Contributor Author

Tried this PR as Supabase is broken on the latest tag and develop:

Error: Error creating room: Could not find the function public.create_room(roomId) in the schema cache

Looks like we're still missing some functions

I wonder if I missed adding the create_room function to schema.sql. I'll check tonight.

@antman1p
Copy link
Contributor Author

Tried this PR as Supabase is broken on the latest tag and develop:
Error: Error creating room: Could not find the function public.create_room(roomId) in the schema cache
Looks like we're still missing some functions

I wonder if I missed adding the create_room function to schema.sql. I'll check tonight.

Yep, somehow I didn't add ANY of the functions to the schema.sql Fixed.

@Hewlbern
Copy link

did this work ongoing?

@antman1p
Copy link
Contributor Author

did this work ongoing?

On my end, the db builds fine. Everything like memories, cache, rooms, actors, etc are writing and reading properly. However, I had an error after I PR'sd with Twitter posting, but the error came back as an empty bracket. I will have to do some debuging tonight arfter work. If @RobertDoc , or someone else would like to test to make sure everything but twitter posting works on their end, that would be great confirmation. Whoever tests will need to copy and paste shcema.sql into their supabase sql editor and add the 2 Supabase variables to their .env, then start Eliza. May also need to test with other things like Discord messaging and such, but everything else seems to be working. We are VERY close.

fix(adapter-supabase): improve memory retrieval and participant state handling

- Fix timestamp handling in getMemories
- Use maybeSingle for participant state queries
- Add proper error handling for memory table lookups
fix(supabase): update get_goals function to handle case sensitivity and column order

- Add quotes to preserve case-sensitive column names
- Fix RETURNS TABLE column order to match goals table structure
- Add table alias to prevent ambiguous column references
- Update WHERE clause to use table alias for column references
@antman1p
Copy link
Contributor Author

did this work ongoing?

OK, everything works now. Tweets are generating without error. I made some changes to the get_goals function in the sdchema.sql, and some changes to ts.index.

@antman1p
Copy link
Contributor Author

We ned a good way to perform robust database testing. I am getting zero errors, but it seems that chat client messaging and discord messaging are responding without context to the question when using supabase, but not with the local sqlite db. I am theorizing it has something to do with memories.

@indowebdeveloper
Copy link

{"code":"42883","details":null,"hint":"No function matches the given name and argument types. You might need to add explicit type casts.","message":"function levenshtein(text, text) does not exist"} getting this error too

@antman1p
Copy link
Contributor Author

{"code":"42883","details":null,"hint":"No function matches the given name and argument types. You might need to add explicit type casts.","message":"function levenshtein(text, text) does not exist"} getting this error too

I added functions in the new commit. Can you please try again. Everything is working on my end with these changes. I just need to test RAGing knowledge.

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Important

Review skipped

Auto 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

The pull request introduces comprehensive changes to the Supabase database adapter, focusing on enhancing memory and knowledge management. The modifications involve restructuring the SQL schema, dropping and recreating functions, and updating the database adapter's implementation. The changes aim to improve data integrity, performance, and flexibility in handling memories, knowledge chunks, and participant interactions.

Changes

File Change Summary
packages/adapter-supabase/schema.sql - Dropped existing functions related to memory and knowledge management
- Created new functions for more efficient memory and knowledge operations
- Added multiple knowledge and memories tables with specific embedding sizes
- Updated permissions for the anon role
- Revised indexing strategy
packages/adapter-supabase/src/index.ts - Added new methods: getParticipantsForRoom, initializeAgentKnowledge, createKnowledgeChunk
- Improved error handling across methods
- Added private methods to determine table names based on embedding sizes
- Enhanced logging and error management for database operations

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

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: 3

🧹 Nitpick comments (2)
packages/adapter-supabase/src/index.ts (2)

617-617: Remove unnecessary continue statement

The continue statement at the end of the loop is redundant and can be safely removed.

Apply this diff to remove it:

-         continue;
🧰 Tools
🪛 Biome (1.9.4)

[error] 617-617: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)


512-517: Validate embeddings upfront to simplify code logic

Consider returning early if the embedding array is invalid or empty to reduce nesting and improve readability.

🧰 Tools
🪛 Biome (1.9.4)

[error] 512-512: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 514-514: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f6f3ec and c781dcb.

📒 Files selected for processing (2)
  • packages/adapter-supabase/schema.sql (11 hunks)
  • packages/adapter-supabase/src/index.ts (21 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/adapter-supabase/src/index.ts

[error] 617-617: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)


[error] 512-512: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 514-514: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (1)
packages/adapter-supabase/schema.sql (1)

354-370: ⚠️ Potential issue

Correct table reference in count_memories function

The count_memories function incorrectly queries public.memories instead of the dynamic table specified by query_table_name.

Apply this diff to fix the table reference:

-         SELECT COUNT(*) FROM public.memories
-         WHERE public.memories."type" = query_table_name
+         EXECUTE format('
+             SELECT COUNT(*) FROM %I
+             WHERE (%L IS NULL OR "roomId" = %L)
+             AND (%L IS FALSE OR "unique" = TRUE)
+         ', query_table_name, query_roomid, query_roomid, query_unique)
+         INTO result;
+         RETURN result;

Likely invalid or redundant comment.

packages/adapter-supabase/src/index.ts Outdated Show resolved Hide resolved
packages/adapter-supabase/src/index.ts Outdated Show resolved Hide resolved
packages/adapter-supabase/schema.sql Show resolved Hide resolved
@antman1p
Copy link
Contributor Author

@coderabbitai generate docstrings

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Caution

No docstrings were generated.

- Removed table name parameter from search_knowledge RPC call
  - Table selection is now handled internally by the function based on embedding size
- Improved error logging for vector operations

The changes fix two main issues:
1. Vector dimension checking using the correct pgvector function
2. JSONB text comparison operations in similarity search

These updates make the vector similarity search more robust and fix compatibility issues with pgvector extension.
- Changed `array_length(query_embedding, 1)` to `vector_dims(query_embedding)` in search_knowledge function
  - array_length doesn't work with pgvector's vector type
  - vector_dims is the correct function for getting vector dimensions
- Added proper text casting for JSONB comparisons in search_knowledge_table
  - Added `::text` casts to fix JSONB comparison operators
  - Fixed ILIKE operations on JSONB fields
- Changed function delimiters from `$$` to `$func$` for better readability
- Added CASCADE to function drops to ensure clean recreation
@antman1p
Copy link
Contributor Author

I'm having some trouble pulling a robust test together for this, but I ma working on it

@wtfsayo wtfsayo changed the title Fix: Made Supabase work chore(fix): supabase adapter Jan 25, 2025
@wtfsayo wtfsayo self-requested a review January 25, 2025 13:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants