Skip to content

feat: extract compute_hash function #929

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

Merged
merged 1 commit into from
May 20, 2025
Merged

feat: extract compute_hash function #929

merged 1 commit into from
May 20, 2025

Conversation

gfyrag
Copy link
Contributor

@gfyrag gfyrag commented May 19, 2025

No description provided.

@gfyrag gfyrag requested a review from a team as a code owner May 19, 2025 10:30
Copy link

coderabbitai bot commented May 19, 2025

Walkthrough

This change adds two PostgreSQL PL/pgSQL functions within a migration: compute_hash, which calculates a SHA-256 hash for log records based on specific fields and previous hashes, and set_log_hash, a trigger function that assigns the computed hash to new log records. Both functions operate within a specified schema.

Changes

File(s) Change Summary
internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql Added compute_hash and set_log_hash PostgreSQL functions for hashing and assigning hashes to log records.

Sequence Diagram(s)

sequenceDiagram
    participant DB as PostgreSQL
    participant Trigger as set_log_hash (trigger)
    participant Func as compute_hash (function)

    Note over DB: On inserting a new log record
    DB->>Trigger: BEFORE INSERT on logs
    Trigger->>DB: Query most recent hash for ledger
    Trigger->>Func: Call compute_hash(previous_hash, new_record)
    Func-->>Trigger: Return computed hash
    Trigger->>DB: Assign hash to new record, continue insert
Loading

Possibly related PRs

  • formancehq/ledger#928: Adds the same compute_hash and set_log_hash functions in the same migration file, indicating direct relation.
  • formancehq/ledger#651: Modifies the set_log_hash function to fix encoding issues; both PRs involve changes to this function.

Suggested reviewers

  • paul-nicolas

Poem

A hash is born with every log,
Secure and neat, no room for fog.
Triggers leap and functions run,
Ensuring hashes, one by one.
In schema fields, the bytes align—
A bunny cheers, “Your hashes shine!” 🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch fix/compute-hash-fn
  • Post Copyable Unit Tests in Comment

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 auto-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.

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.

@gfyrag gfyrag force-pushed the fix/fix-memento-format branch from 154f988 to 53e9152 Compare May 19, 2025 10:31
Copy link

codecov bot commented May 19, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.35%. Comparing base (43d8e72) to head (2506165).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #929      +/-   ##
==========================================
+ Coverage   82.27%   82.35%   +0.07%     
==========================================
  Files         141      141              
  Lines        7786     7786              
==========================================
+ Hits         6406     6412       +6     
+ Misses       1055     1051       -4     
+ Partials      325      323       -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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gfyrag gfyrag force-pushed the fix/fix-memento-format branch from 53e9152 to b1cc5c4 Compare May 19, 2025 10:37
@gfyrag gfyrag force-pushed the fix/compute-hash-fn branch 2 times, most recently from af8b7ff to 8eb0a7d Compare May 19, 2025 10:41
Base automatically changed from fix/fix-memento-format to main May 19, 2025 14:00
@gfyrag gfyrag added this pull request to the merge queue May 19, 2025
github-merge-queue bot pushed a commit that referenced this pull request May 19, 2025
* fix: memento format

* feat: extract compute_hash function
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks May 19, 2025
@gfyrag gfyrag added this pull request to the merge queue May 19, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks May 19, 2025
@gfyrag gfyrag added this pull request to the merge queue May 19, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks May 19, 2025
@gfyrag gfyrag added this pull request to the merge queue May 20, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks May 20, 2025
@gfyrag gfyrag added this pull request to the merge queue May 20, 2025
github-merge-queue bot pushed a commit that referenced this pull request May 20, 2025
* fix: memento format

* feat: extract compute_hash function
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks May 20, 2025
@gfyrag gfyrag added this pull request to the merge queue May 20, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks May 20, 2025
@gfyrag gfyrag added this pull request to the merge queue May 20, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks May 20, 2025
@gfyrag gfyrag force-pushed the fix/compute-hash-fn branch from 8eb0a7d to 2506165 Compare May 20, 2025 17:11
Copy link

@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: 1

🧹 Nitpick comments (5)
internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql (5)

1-4: Mark compute_hash as IMMUTABLE and verify pgcrypto availability.
Since compute_hash is a pure, side-effect-free function, add an IMMUTABLE volatility modifier after RETURNS bytea to enable planner optimizations. Also confirm that the pgcrypto extension (which provides digest) is installed in this schema or include a CREATE EXTENSION IF NOT EXISTS pgcrypto before these definitions to prevent migration failures.

 create or replace function compute_hash(previous_hash bytea, r logs)
-    returns bytea
+    returns bytea
+    immutable
     language plpgsql
 as
 $$

6-7: Use text instead of varchar for unbounded JSON strings.
Even though varchar without a length defaults to unlimited in PostgreSQL, using text makes the intent clear and avoids any accidental constraint.

 declare
-   marshalledAsJSON varchar;
+   marshalledAsJSON text;

10-17: Ensure deterministic, valid JSON-like concatenation.

  • Wrap the data payload in quotes and consider switching to base64 for cross-language consistency.
  • Guard all concatenated fields (not only idempotency_key) against NULL to avoid silent nullification of the entire string.
 select '{' ||
-       '"type":"' || r.type || '",' ||
-       '"data":' || encode(r.memento, 'escape') || ',' ||
+       '"type":"' || coalesce(r.type, '') || '",' ||
+       '"data":"' || encode(r.memento, 'base64') || '",' ||
        '"date":"' || (to_json(r.date::timestamp)#>>'{}') || 'Z",' ||
-       '"idempotencyKey":"' || coalesce(r.idempotency_key, '') || '",' ||
+       '"idempotencyKey":"' || coalesce(r.idempotency_key, '') || '",' ||
        '"id":0,' ||
        '"hash":null' ||
        '}' into marshalledAsJSON;

19-25: Simplify the RETURN by removing the nested SELECT.
In PL/pgSQL you can return the result of public.digest directly without wrapping it in a SELECT.

-   return (
-     select public.digest(
-       case
-         ...
-       end || E'\n', 'sha256'::text
-     )
-   );
+   return public.digest(
+     case
+       ...
+     end || E'\n',
+     'sha256'
+   );

38-42: Add an index to optimize the previous‐hash lookup.
The query

SELECT hash
  FROM logs
 WHERE ledger = new.ledger
 ORDER BY seq DESC
 LIMIT 1;

can become slow on large tables. Consider adding an index on (ledger, seq DESC) if it doesn’t already exist.

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_logs_ledger_seq
  ON {{ .Schema }}.logs (ledger, seq DESC);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 43d8e72 and 2506165.

⛔ Files ignored due to path filters (4)
  • internal/storage/bucket/migrations/35-create-compute-hash-function/notes.yaml is excluded by !**/*.yaml
  • internal/storage/bucket/migrations/36-accounts-recreate-unique-index/notes.yaml is excluded by !**/*.yaml
  • internal/storage/bucket/migrations/37-clean-database/notes.yaml is excluded by !**/*.yaml
  • internal/storage/bucket/migrations/38-logs-async-hash-procedure/notes.yaml is excluded by !**/*.yaml
📒 Files selected for processing (1)
  • internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql (1 hunks)
🔇 Additional comments (2)
internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql (2)

29-33: Verify trigger installation and timing.
This defines the set_log_hash() function, but ensure you create a BEFORE INSERT trigger on logs that invokes it. Without registering the trigger, new rows won’t get their hash populated.

Did you include something like:

CREATE TRIGGER trg_set_log_hash
BEFORE INSERT ON {{ .Schema }}.logs
FOR EACH ROW EXECUTE FUNCTION set_log_hash();

in your migration sequence?


44-46: Confirm correct trigger function execution context.
Assigning new.hash = compute_hash(previousHash, new) requires this to run in a BEFORE INSERT trigger so that new.seq is available (via default) and new.hash is persisted. Please verify the trigger’s configuration matches this requirement.

select '{' ||
'"type":"' || r.type || '",' ||
'"data":' || encode(r.memento, 'escape') || ',' ||
'"date":"' || (to_json(r.date::timestamp)#>>'{}') || 'Z",' ||
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Format timestamps in UTC explicitly.
Casting a timestamptz to timestamp applies the server’s timezone. For a stable hash, format the date in UTC, e.g.:

-  '"date":"' || (to_json(r.date::timestamp)#>>'{}') || 'Z",' ||
+  '"date":"' || to_char(r.date AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') || '",' ||
📝 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
'"date":"' || (to_json(r.date::timestamp)#>>'{}') || 'Z",' ||
'"date":"' || to_char(r.date AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') || '",' ||
🤖 Prompt for AI Agents
In internal/storage/bucket/migrations/35-create-compute-hash-function/up.sql at
line 13, the timestamp is cast to timestamp without timezone, which applies the
server's timezone and can cause inconsistent hashes. Modify the code to
explicitly format the timestamp in UTC by converting the timestamptz to UTC
before formatting, ensuring stable and consistent hash values regardless of
server timezone.

@gfyrag gfyrag added this pull request to the merge queue May 20, 2025
Merged via the queue into main with commit 3b88db5 May 20, 2025
10 checks passed
@gfyrag gfyrag deleted the fix/compute-hash-fn branch May 20, 2025 17:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants