Repository navigation
feat(postgres): set up dual-writes - #6316
Hidden character warning
Conversation
# Conflicts: # AGENTS.md
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #6316 +/- ##
==========================================
+ Coverage 55.83% 56.20% +0.37%
==========================================
Files 223 225 +2
Lines 23001 23458 +457
==========================================
+ Hits 12842 13184 +342
- Misses 10156 10271 +115
Partials 3 3
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
For both vanir signatures, and delete, they have the same issue of:
- datastore/gcs write succeeds
- postresql fails to write
- error is returned and retry is sent
- Upon receiving the retry message, worker checks if it's already done ( vanir signature generated, record withdrawn...etc), then early exit. Leaving postgresql not updated.
There was a problem hiding this comment.
flipped the dual write ordering to do Postgres first. If Datastore/GCS fails after Postgres succeeds, the job will retry later and rewrite when it does succeed.
| if !pgChanged { | ||
| return false, nil | ||
| } | ||
| pgVuln.Modified = timestamppb.New(modified) |
There was a problem hiding this comment.
Hmm should this be checking whether pgVuln's modified is already newer than this modified?
There was a problem hiding this comment.
added a check for this (and for Datastore too!)
There was a problem hiding this comment.
Apparently this leaks POSTGRES_PASSWORD into the vanir signature runner. We'll be fixing that anyway before we restart vanir, so this is probably fine to ignore
There was a problem hiding this comment.
filtered POSTGRES_* env vars from vanir command since it was simple.
| ); | ||
|
|
||
| -- name: SyncAffectedCommits :exec | ||
| WITH old_set AS ( |
There was a problem hiding this comment.
We should check that there's actually a change before we make all the queries and unnests.
| VALUES (@vuln_id, @commits::bytea[]) | ||
| ON CONFLICT (vuln_id) DO UPDATE | ||
| SET commits = EXCLUDED.commits | ||
| WHERE vuln_commits.commits IS DISTINCT FROM EXCLUDED.commits; |
There was a problem hiding this comment.
We can move this up earlier so that it doesn't do all the unnest work before reaching here and realize nothing needs to be done.
e.g.
+changed AS (
+ SELECT COALESCE((SELECT commits FROM existing), ARRAY[]::bytea[]) AS old_commits
+ WHERE (SELECT commits FROM existing) IS DISTINCT FROM @commits::bytea[]
+),
| } else { | ||
| sortedCommits := slices.Clone(req.AffectedCommits.Commits) | ||
| slices.SortFunc(sortedCommits, bytes.Compare) | ||
| sortedCommits = slices.CompactFunc(sortedCommits, bytes.Equal) |
There was a problem hiding this comment.
Commit sorting inside the transaction? This could get pretty big...
There was a problem hiding this comment.
moved sorting outside the transaction
| return err | ||
| } | ||
|
|
||
| var data []byte |
There was a problem hiding this comment.
This is very similar to importer, pls refactor and dedup this.
There was a problem hiding this comment.
extracted to taskmsg.NewUpdateMessage for both importer and recoverer to use
| @@ -130,18 +136,28 @@ func (s *Subscriber) parseVuln(m *pubsub.Message) (*osvschema.Vulnerability, err | |||
| var err error | |||
| data, err = zstd.DecodeTo(data, m.Data) | |||
There was a problem hiding this comment.
The max 10MB encoded size could blow up to a huge amount of memory usage.
You can set a WIthDecoderMaxMemory limit for zstd. This way we at least know when we are causing issues due to too big records.
There was a problem hiding this comment.
using WithDecoderMaxMemory, with 128 MiB
| --zone="$CLUSTER_ZONE" \ | ||
| --project="$PROJECT_ID" | ||
| kubectl create secret generic osv-db-worker-password \ | ||
| --from-literal="password=$PG_WORKER_PASS" \ |
There was a problem hiding this comment.
We should pass password in via stdin, not via cli flags (since anyone on the pc can read the cli flag when the command is running). Not really a big deal since we are all on relatively trusted machines though.
There was a problem hiding this comment.
sending password through stdin via printf into --from-file=password=/dev/stdin
| if len(rawSHA256) == 0 && len(task.RawJSON) > 0 { | ||
| sum := sha256.Sum256(task.RawJSON) | ||
| rawSHA256 = sum[:] | ||
| } |
There was a problem hiding this comment.
postgres.VulnerabilityStore.Write already computes the sha256.Sum256(rawJSON) fallback when req.RawSHA256 is empty, and Datastore doesn't use RawSHA256. We can drop this duplicate fallback (and the "crypto/sha256" import on L5):
--- a/go/internal/worker/engine.go
+++ b/go/internal/worker/engine.go
@@ -2,7 +2,6 @@ package worker
import (
"context"
- "crypto/sha256"
"encoding/hex"
"errors"
"fmt"
@@ -124,10 +123,6 @@ func (e *Engine) handleUpdate(ctx context.Context, task Task) error {
rawSHA256 = decoded
}
}
- if len(rawSHA256) == 0 && len(task.RawJSON) > 0 {
- sum := sha256.Sum256(task.RawJSON)
- rawSHA256 = sum[:]
- }
if err := e.Stores.Vulnerability.Write(ctx, models.WriteRequest{
ID: enriched.GetId(),| } | ||
|
|
||
| // Write atomically updates the base record and its derived indexes. | ||
| func (s *VulnerabilityStore) Write(ctx context.Context, req models.WriteRequest) error { |
There was a problem hiding this comment.
Write can be simplified quite a bit by:
- Dropping the unused
req.Raw == nil && len(req.RawJSON) > 0unmarshal branch (datastore.Writeand all callers either passRawor omit both). - Using
cmp.Or(req.ID, req.Enriched.GetId()). - Moving commit sorting/dedup out before opening the transaction.
- Extracting small
pbTimePtr,derefTime,withTx,upsertRawVulnerability, andupdateAffectedCommitshelpers (which also cleans up the repeated nullable timestamp conversions inGetWithMetadata,ListBySource, andMutate).
Suggested diff:
--- a/go/internal/database/postgres/vulnerability.go
+++ b/go/internal/database/postgres/vulnerability.go
@@ -16,6 +16,7 @@ package postgres
import (
"bytes"
+ "cmp"
"context"
"crypto/sha256"
"errors"
@@ -36,6 +37,7 @@ import (
"github.com/ossf/osv-schema/bindings/go/osvschema"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
)
// isValidPGText reports whether s can be sent as a PostgreSQL UTF-8 TEXT
@@ -227,16 +229,11 @@ func (s *VulnerabilityStore) GetWithMetadata(ctx context.Context, id string) (*o
return nil, nil, err
}
- var modRaw time.Time
- if row.SourceModified != nil {
- modRaw = *row.SourceModified
- }
-
ref := &models.VulnSourceRef{
ID: row.ID,
Source: row.SourceID,
Path: row.SourcePath,
- ModifiedRaw: modRaw,
+ ModifiedRaw: derefTime(row.SourceModified),
}
return v, ref, nil
@@ -296,15 +293,11 @@ func (s *VulnerabilityStore) ListBySource(ctx context.Context, source string, sk
afterPath = r.SourcePath
afterID = r.ID
- var modRaw time.Time
- if r.SourceModified != nil {
- modRaw = *r.SourceModified
- }
ref := &models.VulnSourceRef{
ID: r.ID,
Source: r.SourceID,
Path: r.SourcePath,
- ModifiedRaw: modRaw,
+ ModifiedRaw: derefTime(r.SourceModified),
}
if !yield(ref, nil) {
return
@@ -364,15 +357,51 @@ func marshalVulnJSON(v *osvschema.Vulnerability) ([]byte, error) {
return schema.SanitizeJSON(data), nil
}
+func pbTimePtr(ts *timestamppb.Timestamp) *time.Time {
+ if ts == nil {
+ return nil
+ }
+ t := ts.AsTime().UTC()
+ return &t
+}
+
+func derefTime(t *time.Time) time.Time {
+ if t == nil {
+ return time.Time{}
+ }
+ return *t
+}
+
+func (s *VulnerabilityStore) withTx(ctx context.Context, id string, fn func(*Queries) error) error {
+ beginner, ok := s.db.(txBeginner)
+ if !ok {
+ return fn(s.queries)
+ }
+
+ tx, err := beginner.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to begin transaction for %s: %w", id, err)
+ }
+ defer func() {
+ _ = tx.Rollback(ctx)
+ }()
+
+ if err := fn(s.queries.WithTx(tx)); err != nil {
+ return err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return fmt.Errorf("failed to commit transaction for %s: %w", id, err)
+ }
+
+ return nil
+}
+
// Write atomically updates the base record and its derived indexes.
func (s *VulnerabilityStore) Write(ctx context.Context, req models.WriteRequest) error {
if req.Enriched == nil {
return errors.New("enriched vulnerability is required")
}
- id := req.ID
- if id == "" {
- id = req.Enriched.GetId()
- }
+ id := cmp.Or(req.ID, req.Enriched.GetId())
if id == "" {
return errors.New("vulnerability ID is required")
}
@@ -386,29 +415,17 @@ func (s *VulnerabilityStore) Write(ctx context.Context, req models.WriteRequest)
return fmt.Errorf("failed to marshal enriched JSON for %s: %w", id, err)
}
- hasRaw := req.Raw != nil || len(req.RawJSON) > 0
- rawProto := req.Raw
- var rawJSON []byte
- var rawSHA256 []byte
- if hasRaw {
+ var rawJSON, rawSHA256 []byte
+ if req.Raw != nil {
if len(req.RawJSON) > 0 {
rawJSON = schema.SanitizeJSON(req.RawJSON)
- if rawProto == nil {
- var parsed osvschema.Vulnerability
- if err := (protojson.UnmarshalOptions{DiscardUnknown: true}).Unmarshal(rawJSON, &parsed); err != nil {
- return fmt.Errorf("failed to unmarshal raw JSON for %s: %w", id, err)
- }
- rawProto = &parsed
- }
- } else {
- rawJSON, err = marshalVulnJSON(rawProto)
- if err != nil {
- return fmt.Errorf("failed to marshal raw JSON for %s: %w", id, err)
- }
+ } else if rawJSON, err = marshalVulnJSON(req.Raw); err != nil {
+ return fmt.Errorf("failed to marshal raw JSON for %s: %w", id, err)
}
- if len(req.RawSHA256) > 0 {
- rawSHA256 = req.RawSHA256
- } else {
+
+ rawSHA256 = req.RawSHA256
+ if len(rawSHA256) == 0 {
sum := sha256.Sum256(rawJSON)
rawSHA256 = sum[:]
}
@@ -419,112 +436,92 @@ func (s *VulnerabilityStore) Write(ctx context.Context, req models.WriteRequest)
return fmt.Errorf("failed to compute affected versions for %s: %w", id, err)
}
- q := s.queries
- var tx pgx.Tx
- if beginner, ok := s.db.(txBeginner); ok {
- tx, err = beginner.Begin(ctx)
- if err != nil {
- return fmt.Errorf("failed to begin transaction for %s: %w", id, err)
- }
- defer func() {
- _ = tx.Rollback(ctx)
- }()
- q = s.queries.WithTx(tx)
+ var sortedCommits [][]byte
+ if !req.AffectedCommits.Skip && req.Enriched.GetWithdrawn() == nil && len(req.AffectedCommits.Commits) > 0 {
+ sortedCommits = slices.Clone(req.AffectedCommits.Commits)
+ slices.SortFunc(sortedCommits, bytes.Compare)
+ sortedCommits = slices.CompactFunc(sortedCommits, bytes.Equal)
}
- var rawVulnID *int64
- if hasRaw {
- fetchedAt := time.Now().UTC()
- if req.FetchedAt != nil && !req.FetchedAt.IsZero() {
- fetchedAt = req.FetchedAt.UTC()
- }
- var gitCommit *string
- if req.GitCommitHash != "" {
- gitCommit = &req.GitCommitHash
- }
-
- rawID, err := q.UpsertRawVulnerability(ctx, UpsertRawVulnerabilityParams{
- VulnID: &id,
- SourceID: req.Source,
- SourcePath: req.Path,
- ContentSha256: rawSHA256,
- GitCommitHash: gitCommit,
- GcsGeneration: req.GCSGeneration,
- RawData: rawJSON,
- FetchedAt: fetchedAt,
- })
- if err != nil {
- return fmt.Errorf("failed to upsert raw_vulnerabilities for %s: %w", id, err)
+ return s.withTx(ctx, id, func(q *Queries) error {
+ params := UpsertVulnerabilityParams{
+ ID: id,
+ SourceID: req.Source,
+ SourcePath: req.Path,
+ Modified: req.Enriched.GetModified().AsTime().UTC(),
+ Withdrawn: pbTimePtr(req.Enriched.GetWithdrawn()),
+ Data: enrichedJSON,
+ Proto: enrichedProto,
+ HasRaw: req.Raw != nil,
}
- rawVulnID = &rawID
- }
-
- var sourceModified *time.Time
- var aliasRaw, relatedRaw, upstreamRaw []string
- if rawProto != nil {
- if rawProto.GetModified() != nil {
- t := rawProto.GetModified().AsTime().UTC()
- sourceModified = &t
+ if req.Raw != nil {
+ rawID, err := upsertRawVulnerability(ctx, q, id, req, rawJSON, rawSHA256)
+ if err != nil {
+ return err
+ }
+ params.RawVulnID = &rawID
+ params.SourceModified = pbTimePtr(req.Raw.GetModified())
+ params.AliasRaw = req.Raw.GetAliases()
+ params.RelatedRaw = req.Raw.GetRelated()
+ params.UpstreamRaw = req.Raw.GetUpstream()
}
- aliasRaw = rawProto.GetAliases()
- relatedRaw = rawProto.GetRelated()
- upstreamRaw = rawProto.GetUpstream()
- }
- var withdrawn *time.Time
- if req.Enriched.GetWithdrawn() != nil {
- t := req.Enriched.GetWithdrawn().AsTime().UTC()
- withdrawn = &t
- }
-
- if err := q.UpsertVulnerability(ctx, UpsertVulnerabilityParams{
- ID: id,
- SourceID: req.Source,
- SourcePath: req.Path,
- RawVulnID: rawVulnID,
- Modified: req.Enriched.GetModified().AsTime().UTC(),
- SourceModified: sourceModified,
- Withdrawn: withdrawn,
- AliasRaw: aliasRaw,
- RelatedRaw: relatedRaw,
- UpstreamRaw: upstreamRaw,
- Data: enrichedJSON,
- Proto: enrichedProto,
- HasRaw: hasRaw,
- }); err != nil {
- return fmt.Errorf("failed to upsert vulnerabilities for %s: %w", id, err)
- }
+ if err := q.UpsertVulnerability(ctx, params); err != nil {
+ return fmt.Errorf("failed to upsert vulnerabilities for %s: %w", id, err)
+ }
+ if err := updateAffectedVersions(ctx, q, id, affectedVersions); err != nil {
+ return err
+ }
+ return updateAffectedCommits(ctx, q, id, req.AffectedCommits.Skip, sortedCommits)
+ })
+}
- if err := updateAffectedVersions(ctx, q, id, affectedVersions); err != nil {
- return err
+func upsertRawVulnerability(ctx context.Context, q *Queries, id string, req models.WriteRequest, rawJSON, rawSHA256 []byte) (int64, error) {
+ fetchedAt := time.Now().UTC()
+ if req.FetchedAt != nil && !req.FetchedAt.IsZero() {
+ fetchedAt = req.FetchedAt.UTC()
}
+ var gitCommit *string
+ if req.GitCommitHash != "" {
+ gitCommit = &req.GitCommitHash
+ }
- if !req.AffectedCommits.Skip {
- if req.Enriched.GetWithdrawn() != nil || len(req.AffectedCommits.Commits) == 0 {
- if err := q.ClearAffectedCommits(ctx, id); err != nil {
- return fmt.Errorf("failed to clear affected_commits for %s: %w", id, err)
- }
- } else {
- sortedCommits := slices.Clone(req.AffectedCommits.Commits)
- slices.SortFunc(sortedCommits, bytes.Compare)
- sortedCommits = slices.CompactFunc(sortedCommits, bytes.Equal)
-
- if err := q.SyncAffectedCommits(ctx, SyncAffectedCommitsParams{
- VulnID: id,
- Commits: sortedCommits,
- }); err != nil {
- return fmt.Errorf("failed to sync affected_commits for %s: %w", id, err)
- }
- }
+ rawID, err := q.UpsertRawVulnerability(ctx, UpsertRawVulnerabilityParams{
+ VulnID: &id,
+ SourceID: req.Source,
+ SourcePath: req.Path,
+ ContentSha256: rawSHA256,
+ GitCommitHash: gitCommit,
+ GcsGeneration: req.GCSGeneration,
+ RawData: rawJSON,
+ FetchedAt: fetchedAt,
+ })
+ if err != nil {
+ return 0, fmt.Errorf("failed to upsert raw_vulnerabilities for %s: %w", id, err)
}
- if tx != nil {
- if err := tx.Commit(ctx); err != nil {
- return fmt.Errorf("failed to commit transaction for %s: %w", id, err)
+ return rawID, nil
+}
+
+func updateAffectedCommits(ctx context.Context, q *Queries, id string, skip bool, sortedCommits [][]byte) error {
+ if skip {
+ return nil
+ }
+ if len(sortedCommits) == 0 {
+ if err := q.ClearAffectedCommits(ctx, id); err != nil {
+ return fmt.Errorf("failed to clear affected_commits for %s: %w", id, err)
}
+
+ return nil
}
+ if err := q.SyncAffectedCommits(ctx, SyncAffectedCommitsParams{
+ VulnID: id,
+ Commits: sortedCommits,
+ }); err != nil {
+ return fmt.Errorf("failed to sync affected_commits for %s: %w", id, err)
+ }
return nil
}
@@ -641,15 +638,9 @@ func (s *VulnerabilityStore) Mutate(ctx context.Context, id string, mutateFn mod
return false, fmt.Errorf("failed to marshal mutated JSON for %s: %w", id, err)
}
- var withdrawn *time.Time
- if v.GetWithdrawn() != nil {
- t := v.GetWithdrawn().AsTime().UTC()
- withdrawn = &t
- }
-
_, err = s.queries.UpdateVulnerabilityOnMutate(ctx, UpdateVulnerabilityOnMutateParams{
Modified: v.GetModified().AsTime().UTC(),
- Withdrawn: withdrawn,
+ Withdrawn: pbTimePtr(v.GetWithdrawn()),
Data: newJSON,
Proto: newProto,
ID: id,# Conflicts: # AGENTS.md # deployment/clouddeploy/gke-workers/base/core/workers.yaml # deployment/clouddeploy/gke-workers/base/extra/workers-cves.yaml # deployment/clouddeploy/gke-workers/base/extra/workers-reimport.yaml # deployment/clouddeploy/gke-workers/environments/oss-vdb-test/workers.yaml # deployment/clouddeploy/gke-workers/environments/private/workers.yaml # go/internal/worker/subscriber_test.go
(Sorry this PR is so big, a lot of things ended up having to be done at the same time)
Set up dual-writing infrastructure for Postgres in the places where vulns get written:
VulnerabilityStorefor postgres (splitting thequeries.sqlinto files corresponding to the go files they're used in)raw_vulnerabilitiesandhistoric_vulnerabilitiesto be written with all needed fieldsI may have to make a follow-up PR fairly quickly to bump the CPUs of the postgres if affected commits are too plentiful.
In a future PR, I plan to re-jig the tests so they spin up postgres in a docker container instead of trying to mock all the endpoints, so we can make sure our queries actually work properly.