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

VReplication: Support binlog_row_value_options=PARTIAL_JSON #17345

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

Conversation

mattlord
Copy link
Contributor

@mattlord mattlord commented Dec 9, 2024

Description

This PR adds support for --binlog-row-value-options=PARTIAL_JSON. You can read more about this here.

This can offer big wins in specific cases. For example...

  1. Let's say that you have a table with 1 JSON column, and the JSON document is often large.
  2. You update just a single row, to update $.price from 99.99 to 102.99 (inflation) and the original JSON document is 5MiB.
  3. Without binlog_row_value_options=PARTIAL_JSON the binlog event will have the full 5MiB document in the BEFORE (original) and AFTER (updated) images. So 10MiB now.
  4. With the option enabled, the BEFORE image still has the 5MiB document but the AFTER image only has a handful of bytes to represent the diff operation, JSON_REPLACE in this case, along with the path of $.price and the value of 102.99. So we've cut the bytes stored on disk, sent over the wire, and processed in memory by ~ 1/2.

Now if you imagine that instead of updating a single row, you updated 10,000 rows... let's say to remove the $.on_sale flag on the documents that had it set (Black Friday is over), you can see the big savings that comes with it.

Important

With this option enabled, JSON columns that are NOT updated when a row is modified are elided from the AFTER images (similar to the binlog_row_image=NOBLOB behavior with BLOB/TEXT columns). So this also offers a big potential savings as you may be updating 10,000 rows in a table that happens to have a JSON column, but you're only changing some other column value(s).

Manual test:

make build

cd examples/local

./101_initial_cluster.sh; mysql < ../common/insert_commerce_data.sql; ./201_customer_tablets.sh
  
alias vtctldclient='command vtctldclient --server=localhost:15999'
  
mysql commerce -e "alter table customer add jd json; update customer set jd = '{\"salary\":100}'; update customer set jd = '{\"salary\":99}' where customer_id in (2,3,4)"
  
for uid in $(vtctldclient GetTablets | awk '{print $1}' | cut -d- -f2 | bc); do
  command mysql -u root --socket "${VTDATAROOT}/vt_0000000${uid}/mysql.sock" -e "set @@global.binlog_row_value_options=PARTIAL_JSON; set @@global.general_log=ON"
done
  
./202_move_tables.sh
  
commerce_primary_uid=$(vtctldclient GetTablets --keyspace commerce --tablet-type primary --shard "0" | awk '{print $1}' | cut -d- -f2 | bc)
customer_primary_uid=$(vtctldclient GetTablets --keyspace customer --tablet-type primary --shard "0" | awk '{print $1}' | cut -d- -f2 | bc)
  
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_SET(jd, '$.role', 'manager')"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_SET(jd, '$.color', 'red')"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set email = concat('new', email)"
  
sleep 2
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${customer_primary_uid}/mysql.sock" vt_customer -e "select * from customer"
  
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_SET(jd, '$.day', 'wednesday')"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_INSERT(JSON_REPLACE(jd, '$.day', 'friday'), '$.favorite_color', 'black')"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_SET(JSON_REMOVE(JSON_REPLACE(jd, '$.day', 'monday'), '$.favorite_color'), '$.hobby', 'skiing') where customer_id = 3"
  
sleep 2
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${customer_primary_uid}/mysql.sock" vt_customer -e "select * from customer"
  
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_SET(JSON_REMOVE(JSON_REPLACE(jd, '$.day', 'tuesday'), '$.favorite_color'), '$.hobby', 'skiing') where customer_id = 4"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_SET(JSON_SET(jd, '$.salary', 110), '$.role', 'IC') where customer_id = 4"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = JSON_SET(jd, '$.misc', '{\"address\":\"1012 S Park\", \"town\":\"Hastings\", \"state\":\"MI\"}') where customer_id = 1"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "insert into customer (customer_id, email) values (10, '[email protected]'), (11, '[email protected]')"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = '\"null\"' where customer_id = 10"
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set jd = 'null' where customer_id = 11"
  
sleep 2
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${customer_primary_uid}/mysql.sock" vt_customer -e "select * from customer"
  
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${commerce_primary_uid}/mysql.sock" vt_commerce -e "update customer set customer_id=customer_id+100, jd=JSON_SET(jd, '$.day', 'friday')"
  
sleep 2
command mysql -u root --socket "${VTDATAROOT}/vt_0000000${customer_primary_uid}/mysql.sock" vt_customer -e "select * from customer"

With the final result:

+-------------+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| customer_id | email                  | jd                                                                                                                                                                               |
+-------------+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|         101 | [email protected]    | {"day": "friday", "misc": "{\"address\":\"1012 S Park\", \"town\":\"Hastings\", \"state\":\"MI\"}", "role": "manager", "color": "red", "salary": 100, "favorite_color": "black"} |
|         102 | [email protected]      | {"day": "friday", "role": "manager", "color": "red", "salary": 99, "favorite_color": "black"}                                                                                    |
|         103 | [email protected]  | {"day": "friday", "role": "manager", "color": "red", "hobby": "skiing", "salary": 99}                                                                                            |
|         104 | [email protected]      | {"day": "friday", "role": "IC", "color": "red", "hobby": "skiing", "salary": 110}                                                                                                |
|         105 | [email protected]      | {"day": "friday", "role": "manager", "color": "red", "salary": 100, "favorite_color": "black"}                                                                                   |
|         110 | [email protected]  | "null"                                                                                                                                                                           |
|         111 | [email protected] | null                                                                                                                                                                             |
+-------------+------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Related Issue(s)

Checklist

@mattlord mattlord added Type: Enhancement Logical improvement (somewhere between a bug and feature) Component: VReplication labels Dec 9, 2024
Copy link
Contributor

vitess-bot bot commented Dec 9, 2024

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@vitess-bot vitess-bot bot added NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says labels Dec 9, 2024
@mattlord mattlord removed NeedsWebsiteDocsUpdate What it says NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Dec 9, 2024
@github-actions github-actions bot added this to the v22.0.0 milestone Dec 9, 2024
@mattlord mattlord force-pushed the vrepl_partial_json branch 3 times, most recently from 1859876 to a44e7e5 Compare December 9, 2024 00:23
Copy link

codecov bot commented Dec 9, 2024

Codecov Report

Attention: Patch coverage is 59.04762% with 129 lines in your changes missing coverage. Please review.

Project coverage is 67.61%. Comparing base (dd4ec2e) to head (27edece).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...blet/tabletmanager/vreplication/replicator_plan.go 26.21% 76 Missing ⚠️
go/test/utils/binlog.go 48.00% 13 Missing ⚠️
go/mysql/binlog/binlog_json.go 89.71% 11 Missing ⚠️
go/mysql/binlog/rbr.go 38.46% 8 Missing ⚠️
...t/tabletmanager/vreplication/table_plan_partial.go 0.00% 8 Missing ⚠️
go/vt/vttablet/tabletserver/vstreamer/vstreamer.go 65.21% 8 Missing ⚠️
go/mysql/binlog_event_rbr.go 90.00% 3 Missing ⚠️
go/mysql/binlog_event_filepos.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #17345      +/-   ##
==========================================
- Coverage   67.64%   67.61%   -0.04%     
==========================================
  Files        1582     1583       +1     
  Lines      254000   254321     +321     
==========================================
+ Hits       171826   171952     +126     
- Misses      82174    82369     +195     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Signed-off-by: Matt Lord <[email protected]>
Signed-off-by: Matt Lord <[email protected]>
Signed-off-by: Matt Lord <[email protected]>
Signed-off-by: Matt Lord <[email protected]>
Signed-off-by: Matt Lord <[email protected]>
@@ -111,7 +111,7 @@ jobs:
- name: Upload coverage reports to codecov.io
if: steps.changes.outputs.changed_files == 'true'
uses: codecov/codecov-action@v4
uses: codecov/codecov-action@015f24e6818733317a2da2edd6290ab26238649a # https://github.com/codecov/codecov-action/releases/tag/v5.0.7
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This didn't help with the periodic failures, but good to upgrade anyway as the latest GA is 5.1.

Comment on lines +526 to +530
if !isBitSet(rowChange.DataColumns.Cols, i) {
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL,
"binary log event missing a needed value for %s.%s due to not using binlog-row-image=FULL; you will need to re-run the workflow with binlog-row-image=FULL",
tp.TargetName, field.Name)
}
Copy link
Contributor Author

@mattlord mattlord Dec 19, 2024

Choose a reason for hiding this comment

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

This fixes a bug we had with NOBLOB support. Without this, the blob/text field value would be silently lost (detected by vdiff). Since NOBLOB support is experimental (even in v22), I do not think we need to backport it.

Comment on lines +637 to +650
if field.Type == querypb.Type_JSON {
var jsVal *sqltypes.Value
if vals[n].IsNull() { // An SQL NULL and not an actual JSON value
jsVal = &sqltypes.NULL
} else { // A JSON value (which may be a JSON null literal value)
jsVal, err = vjson.MarshalSQLValue(vals[n].Raw())
if err != nil {
return nil, err
}
}
bindVar, err = tp.bindFieldVal(field, jsVal)
} else {
bindVar, err = tp.bindFieldVal(field, &vals[n])
}
Copy link
Contributor Author

@mattlord mattlord Dec 19, 2024

Choose a reason for hiding this comment

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

This was a bug exposed in the VPlayerBatching, which was enabled by default in v22. Prior to v22 it was experimental and thus I don't think we need to backport this fix.

1. Use iota for op type

2. Optimize binary diff parsing when 0 bytes (don't allocate)

Signed-off-by: Matt Lord <[email protected]>
Signed-off-by: Matt Lord <[email protected]>
@mattlord mattlord removed the release notes (needs details) This PR needs to be listed in the release notes in a dedicated section (deprecation notice, etc...) label Dec 21, 2024
mattlord added a commit to vitessio/website that referenced this pull request Dec 21, 2024
@mattlord mattlord removed the NeedsWebsiteDocsUpdate What it says label Dec 21, 2024
mattlord added a commit to vitessio/website that referenced this pull request Dec 21, 2024
mattlord added a commit to vitessio/website that referenced this pull request Dec 21, 2024
Copy link
Contributor

@rohit-nayak-ps rohit-nayak-ps left a comment

Choose a reason for hiding this comment

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

Nice work!

Now we're covering all JSON types:
 - string
 - number
 - object (JSON object)
 - array
 - boolean
 - null

Signed-off-by: Matt Lord <[email protected]>
Copy link
Contributor

@shlomi-noach shlomi-noach left a comment

Choose a reason for hiding this comment

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

Looks good! Asked for some comment clarifications, see inline. Basically I need a braindump of your knowledge to get a better understanding of how this works (the code is mostly too complex to just figure this out from the code).

Comment on lines 91 to 106
for pos < len(data) {
opType := jsonDiffOp(data[pos])
pos++
if outer {
innerStr = diff.String()
diff.Reset()
}
switch opType {
case jsonDiffOpReplace:
diff.WriteString("JSON_REPLACE(")
case jsonDiffOpInsert:
diff.WriteString("JSON_INSERT(")
case jsonDiffOpRemove:
diff.WriteString("JSON_REMOVE(")
default:
// Can be a JSON null.
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you generally clarify (by code comments) what's going on here? (And otherwise in the rest of the function). I feel like there's some intimate knowledge here that I'm missing. What exactly needs to be done? What are we solving?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added here: 5deec92

// IsDeleteRows returns true if this is a DELETE_ROWS_EVENT.
IsDeleteRows() bool

// IsPseudo is for custom implementations of GTID.
Copy link
Contributor

Choose a reason for hiding this comment

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

Please explain the purpose of this Pseudo() function? What are custom implementations of GTID? (Also, I'm not sure I follow the connection to partial JSON. Is this specific for testing?)

Copy link
Contributor Author

@mattlord mattlord Dec 23, 2024

Choose a reason for hiding this comment

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

I don't know the answer to these things either. 🙂 I only moved it to more logically group the IsBlank functions together. I did not add it here.

It looks like dead code as it's only ever set to false:

go/mysql/binlog_event.go:       // IsPseudo is for custom implementations of GTID.
go/mysql/binlog_event.go:       IsPseudo() bool
go/mysql/binlog_event_common.go:// IsPseudo is always false for a native binlogEvent.
go/mysql/binlog_event_common.go:func (ev binlogEvent) IsPseudo() bool {
go/mysql/binlog_event_filepos.go:func (ev filePosFakeEvent) IsPseudo() bool {
go/vt/binlog/binlog_streamer.go:                case ev.IsPseudo():

It was added 7 years ago in #3950

@GrahamCampbell
Copy link
Contributor

I'd be curious how battle tested this actually is, and if there are any MySQL bugs that may cause drift.

Signed-off-by: Matt Lord <[email protected]>
Signed-off-by: Matt Lord <[email protected]>
@mattlord
Copy link
Contributor Author

mattlord commented Dec 23, 2024

I'd be curious how battle tested this actually is, and if there are any MySQL bugs that may cause drift.

I have no idea how widely the option is used across the global set of MySQL installations. I don't see any known bugs:

It's worth noting that this feature has existed in MySQL GA releases now for over 6 years.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: VReplication Type: Enhancement Logical improvement (somewhere between a bug and feature)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature Request: Support more efficient JSON replication
4 participants