You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

376 lines
17 KiB

Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Allow hiding of reblogs from followed users (#5762) * Allow hiding of reblogs from followed users This adds a new entry to the account menu to allow users to hide future reblogs from a user (and then if they've done that, to show future reblogs instead). This does not remove or add historical reblogs from/to the user's timeline; it only affects new statuses. The API for this operates by sending a "reblogs" key to the follow endpoint. If this is sent when starting a new follow, it will be respected from the beginning of the follow relationship (even if the follow request must be approved by the followee). If this is sent when a follow relationship already exists, it will simply update the existing follow relationship. As with the notification muting, this will now return an object ({reblogs: [true|false]}) or false for each follow relationship when requesting relationship information for an account. This should cause few issues due to an object being truthy in many languages, but some modifications may need to be made in pickier languages. Database changes: adds a show_reblogs column (default true, non-nullable) to the follows and follow_requests tables. Because these are non-nullable, we use the existing MigrationHelpers to perform this change without locking those tables, although the tables are likely to be small anyway. Tests included. See also <https://github.com/glitch-soc/mastodon/pull/212>. * Rubocop fixes * Code review changes * Test fixes This patchset closes #648 and resolves #3271. * Rubocop fix * Revert reblogs defaulting in argument, fix tests It turns out we needed this for the same reason we needed it in muting: if nil gets passed in somehow (most usually by an API client not passing any value), we need to detect and handle it. We could specify a default in the parameter and then also catch nil, but there's no great reason to duplicate the default value.
6 years ago
Allow hiding of reblogs from followed users (#5762) * Allow hiding of reblogs from followed users This adds a new entry to the account menu to allow users to hide future reblogs from a user (and then if they've done that, to show future reblogs instead). This does not remove or add historical reblogs from/to the user's timeline; it only affects new statuses. The API for this operates by sending a "reblogs" key to the follow endpoint. If this is sent when starting a new follow, it will be respected from the beginning of the follow relationship (even if the follow request must be approved by the followee). If this is sent when a follow relationship already exists, it will simply update the existing follow relationship. As with the notification muting, this will now return an object ({reblogs: [true|false]}) or false for each follow relationship when requesting relationship information for an account. This should cause few issues due to an object being truthy in many languages, but some modifications may need to be made in pickier languages. Database changes: adds a show_reblogs column (default true, non-nullable) to the follows and follow_requests tables. Because these are non-nullable, we use the existing MigrationHelpers to perform this change without locking those tables, although the tables are likely to be small anyway. Tests included. See also <https://github.com/glitch-soc/mastodon/pull/212>. * Rubocop fixes * Code review changes * Test fixes This patchset closes #648 and resolves #3271. * Rubocop fix * Revert reblogs defaulting in argument, fix tests It turns out we needed this for the same reason we needed it in muting: if nil gets passed in somehow (most usually by an API client not passing any value), we need to detect and handle it. We could specify a default in the parameter and then also catch nil, but there's no great reason to duplicate the default value.
6 years ago
Allow hiding of reblogs from followed users (#5762) * Allow hiding of reblogs from followed users This adds a new entry to the account menu to allow users to hide future reblogs from a user (and then if they've done that, to show future reblogs instead). This does not remove or add historical reblogs from/to the user's timeline; it only affects new statuses. The API for this operates by sending a "reblogs" key to the follow endpoint. If this is sent when starting a new follow, it will be respected from the beginning of the follow relationship (even if the follow request must be approved by the followee). If this is sent when a follow relationship already exists, it will simply update the existing follow relationship. As with the notification muting, this will now return an object ({reblogs: [true|false]}) or false for each follow relationship when requesting relationship information for an account. This should cause few issues due to an object being truthy in many languages, but some modifications may need to be made in pickier languages. Database changes: adds a show_reblogs column (default true, non-nullable) to the follows and follow_requests tables. Because these are non-nullable, we use the existing MigrationHelpers to perform this change without locking those tables, although the tables are likely to be small anyway. Tests included. See also <https://github.com/glitch-soc/mastodon/pull/212>. * Rubocop fixes * Code review changes * Test fixes This patchset closes #648 and resolves #3271. * Rubocop fix * Revert reblogs defaulting in argument, fix tests It turns out we needed this for the same reason we needed it in muting: if nil gets passed in somehow (most usually by an API client not passing any value), we need to detect and handle it. We could specify a default in the parameter and then also catch nil, but there's no great reason to duplicate the default value.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
Non-Serial ("Snowflake") IDs (#4801) * Use non-serial IDs This change makes a number of nontrivial tweaks to the data model in Mastodon: * All IDs are now 8 byte integers (rather than mixed 4- and 8-byte) * IDs are now assigned as: * Top 6 bytes: millisecond-resolution time from epoch * Bottom 2 bytes: serial (within the millisecond) sequence number * See /lib/tasks/db.rake's `define_timestamp_id` for details, but note that the purpose of these changes is to make it difficult to determine the number of objects in a table from the ID of any object. * The Redis sorted set used for the feed will have values used to look up toots, rather than scores. This is almost always the same as the existing behavior, except in the case of boosted toots. This change was made because Redis stores scores as double-precision floats, which cannot store the new ID format exactly. Note that this doesn't cause problems with sorting/pagination, because ZREVRANGEBYSCORE sorts lexicographically when scores are tied. (This will still cause sorting issues when the ID gains a new significant digit, but that's extraordinarily uncommon.) Note a couple of tradeoffs have been made in this commit: * lib/tasks/db.rake is used to enforce many/most column constraints, because this commit seems likely to take a while to bring upstream. Enforcing a post-migrate hook is an easier way to maintain the code in the interim. * Boosted toots will appear in the timeline as many times as they have been boosted. This is a tradeoff due to the way the feed is saved in Redis at the moment, but will be handled by a future commit. This would effectively close Mastodon's #1059, as it is a snowflake-like system of generating IDs. However, given how involved the changes were simply within Mastodon, it may have unexpected interactions with some clients, if they store IDs as doubles (or as 4-byte integers). This was a problem that Twitter ran into with their "snowflake" transition, particularly in JavaScript clients that treated IDs as JS integers, rather than strings. It therefore would be useful to test these changes at least in the web interface and popular clients before pushing them to all users. * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Restructure feed pushes/unpushes This was necessary because the previous behavior used Redis zset scores to identify statuses, but those are IEEE double-precision floats, so we can't actually use them to identify all 64-bit IDs. However, it leaves the code in a much better state for refactoring reblog handling / coalescing. Feed-management code has been consolidated in FeedManager, including: * BatchedRemoveStatusService no longer directly manipulates feed zsets * RemoveStatusService no longer directly manipulates feed zsets * PrecomputeFeedService has moved its logic to FeedManager#populate_feed (PrecomputeFeedService largely made lots of calls to FeedManager, but didn't follow the normal adding-to-feed process.) This has the effect of unifying all of the feed push/unpush logic in FeedManager, making it much more tractable to update it in the future. Due to some additional checks that must be made during, for example, batch status removals, some Redis pipelining has been removed. It does not appear that this should cause significantly increased load, but if necessary, some optimizations are possible in batch cases. These were omitted in the pursuit of simplicity, but a batch_push and batch_unpush would be possible in the future. Tests were added to verify that pushes happen under expected conditions, and to verify reblog behavior (both on pushing and unpushing). In the case of unpushing, this includes testing behavior that currently leads to confusion such as Mastodon's #2817, but this codifies that the behavior is currently expected. * Rubocop fixes I could swear I made these changes already, but I must have lost them somewhere along the line. * Address review comments This addresses the first two comments from review of this feature: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336735 https://github.com/tootsuite/mastodon/pull/4801#discussion_r139336931 This adds an optional argument to FeedManager#key, the subtype of feed key to generate. It also tests to ensure that FeedManager's settings are such that reblogs won't be tracked forever. * Hardcode IdToBigints migration columns This addresses a comment during review: https://github.com/tootsuite/mastodon/pull/4801#discussion_r139337452 This means we'll need to make sure that all _id columns going forward are bigints, but that should happen automatically in most cases. * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Only implement timestamp IDs for Status IDs Per discussion in #4801, this is only being merged in for Status IDs at this point. We do this in a migration, as there is no longer use for a post-migration hook. We keep the initialization of the timestamp_id function as a Rake task, as it is also needed after db:schema:load (as db/schema.rb doesn't store Postgres functions). * Change internal streaming payloads to stringified IDs as well This is equivalent to 591a9af356faf2d5c7e66e3ec715502796c875cd from #5019, with an extra change for the addition to FeedManager#unpush. * Ensure we have a status_id_seq sequence Apparently this is not a given when specifying a custom ID function, so now we ensure it gets created. This uses the generic version of this function to more easily support adding additional tables with timestamp IDs in the future, although it would be possible to cut this down to a less generic version if necessary. It is only run during db:schema:load or the relevant migration, so the overhead is extraordinarily minimal. * Transition reblogs to new Redis format This provides a one-way migration to transition old Redis reblog entries into the new format, with a separate tracking entry for reblogs. It is not invertible because doing so could (if timestamp IDs are used) require a database query for each status in each users' feed, which is likely to be a significant toll on major instances. * Address review comments from @akihikodaki No functional changes. * Additional review changes * Heredoc cleanup * Run db:schema:load hooks for test in development This matches the behavior in Rails' ActiveRecord::Tasks::DatabaseTasks.each_current_configuration, which would otherwise break `rake db:setup` in development. It also moves some functionality out to a library, which will be a good place to put additional related functionality in the near future.
6 years ago
  1. # frozen_string_literal: true
  2. require 'singleton'
  3. class FeedManager
  4. include Singleton
  5. include Redisable
  6. MAX_ITEMS = 400
  7. # Must be <= MAX_ITEMS or the tracking sets will grow forever
  8. REBLOG_FALLOFF = 40
  9. def with_active_accounts(&block)
  10. Account.joins(:user).where('users.current_sign_in_at > ?', User::ACTIVE_DURATION.ago).find_each(&block)
  11. end
  12. def key(type, id, subtype = nil)
  13. return "feed:#{type}:#{id}" unless subtype
  14. "feed:#{type}:#{id}:#{subtype}"
  15. end
  16. def filter?(timeline_type, status, receiver_id)
  17. if timeline_type == :home
  18. filter_from_home?(status, receiver_id, build_crutches(receiver_id, [status]))
  19. elsif timeline_type == :mentions
  20. filter_from_mentions?(status, receiver_id)
  21. else
  22. false
  23. end
  24. end
  25. def push_to_home(account, status)
  26. return false unless add_to_feed(:home, account.id, status, account.user&.aggregates_reblogs?)
  27. trim(:home, account.id)
  28. PushUpdateWorker.perform_async(account.id, status.id, "timeline:#{account.id}") if push_update_required?("timeline:#{account.id}")
  29. true
  30. end
  31. def unpush_from_home(account, status)
  32. return false unless remove_from_feed(:home, account.id, status, account.user&.aggregates_reblogs?)
  33. redis.publish("timeline:#{account.id}", Oj.dump(event: :delete, payload: status.id.to_s))
  34. true
  35. end
  36. def push_to_list(list, status)
  37. if status.reply? && status.in_reply_to_account_id != status.account_id
  38. should_filter = status.in_reply_to_account_id != list.account_id
  39. should_filter &&= !ListAccount.where(list_id: list.id, account_id: status.in_reply_to_account_id).exists?
  40. return false if should_filter
  41. end
  42. return false unless add_to_feed(:list, list.id, status, list.account.user&.aggregates_reblogs?)
  43. trim(:list, list.id)
  44. PushUpdateWorker.perform_async(list.account_id, status.id, "timeline:list:#{list.id}") if push_update_required?("timeline:list:#{list.id}")
  45. true
  46. end
  47. def unpush_from_list(list, status)
  48. return false unless remove_from_feed(:list, list.id, status, list.account.user&.aggregates_reblogs?)
  49. redis.publish("timeline:list:#{list.id}", Oj.dump(event: :delete, payload: status.id.to_s))
  50. true
  51. end
  52. def trim(type, account_id)
  53. timeline_key = key(type, account_id)
  54. reblog_key = key(type, account_id, 'reblogs')
  55. # Remove any items past the MAX_ITEMS'th entry in our feed
  56. redis.zremrangebyrank(timeline_key, 0, -(FeedManager::MAX_ITEMS + 1))
  57. # Get the score of the REBLOG_FALLOFF'th item in our feed, and stop
  58. # tracking anything after it for deduplication purposes.
  59. falloff_rank = FeedManager::REBLOG_FALLOFF - 1
  60. falloff_range = redis.zrevrange(timeline_key, falloff_rank, falloff_rank, with_scores: true)
  61. falloff_score = falloff_range&.first&.last&.to_i || 0
  62. # Get any reblogs we might have to clean up after.
  63. redis.zrangebyscore(reblog_key, 0, falloff_score).each do |reblogged_id|
  64. # Remove it from the set of reblogs we're tracking *first* to avoid races.
  65. redis.zrem(reblog_key, reblogged_id)
  66. # Just drop any set we might have created to track additional reblogs.
  67. # This means that if this reblog is deleted, we won't automatically insert
  68. # another reblog, but also that any new reblog can be inserted into the
  69. # feed.
  70. redis.del(key(type, account_id, "reblogs:#{reblogged_id}"))
  71. end
  72. end
  73. def merge_into_timeline(from_account, into_account)
  74. timeline_key = key(:home, into_account.id)
  75. aggregate = into_account.user&.aggregates_reblogs?
  76. query = from_account.statuses.where(visibility: [:public, :unlisted, :private]).includes(:preloadable_poll, reblog: :account).limit(FeedManager::MAX_ITEMS / 4)
  77. if redis.zcard(timeline_key) >= FeedManager::MAX_ITEMS / 4
  78. oldest_home_score = redis.zrange(timeline_key, 0, 0, with_scores: true).first.last.to_i
  79. query = query.where('id > ?', oldest_home_score)
  80. end
  81. statuses = query.to_a
  82. crutches = build_crutches(into_account.id, statuses)
  83. statuses.each do |status|
  84. next if filter_from_home?(status, into_account.id, crutches)
  85. add_to_feed(:home, into_account.id, status, aggregate)
  86. end
  87. trim(:home, into_account.id)
  88. end
  89. def unmerge_from_timeline(from_account, into_account)
  90. timeline_key = key(:home, into_account.id)
  91. oldest_home_score = redis.zrange(timeline_key, 0, 0, with_scores: true)&.first&.last&.to_i || 0
  92. from_account.statuses.select('id, reblog_of_id').where('id > ?', oldest_home_score).reorder(nil).find_each do |status|
  93. remove_from_feed(:home, into_account.id, status, into_account.user&.aggregates_reblogs?)
  94. end
  95. end
  96. def clear_from_timeline(account, target_account)
  97. # Clear from timeline all statuses from or mentionning target_account
  98. timeline_key = key(:home, account.id)
  99. timeline_status_ids = redis.zrange(timeline_key, 0, -1)
  100. statuses = Status.where(id: timeline_status_ids).select(:id, :reblog_of_id, :account_id).to_a
  101. reblogged_ids = Status.where(id: statuses.map(&:reblog_of_id).compact, account: target_account).pluck(:id)
  102. with_mentions_ids = Mention.active.where(status_id: statuses.flat_map { |s| [s.id, s.reblog_of_id] }.compact, account: target_account).pluck(:status_id)
  103. target_statuses = statuses.filter do |status|
  104. status.account_id == target_account.id || reblogged_ids.include?(status.reblog_of_id) || with_mentions_ids.include?(status.id) || with_mentions_ids.include?(status.reblog_of_id)
  105. end
  106. target_statuses.each do |status|
  107. unpush_from_home(account, status)
  108. end
  109. end
  110. def populate_feed(account)
  111. limit = FeedManager::MAX_ITEMS / 2
  112. aggregate = account.user&.aggregates_reblogs?
  113. timeline_key = key(:home, account.id)
  114. account.statuses.where.not(visibility: :direct).limit(limit).each do |status|
  115. add_to_feed(:home, account.id, status, aggregate)
  116. end
  117. account.following.includes(:account_stat).find_each do |target_account|
  118. if redis.zcard(timeline_key) >= limit
  119. oldest_home_score = redis.zrange(timeline_key, 0, 0, with_scores: true).first.last.to_i
  120. last_status_score = Mastodon::Snowflake.id_at(account.last_status_at)
  121. # If the feed is full and this account has not posted more recently
  122. # than the last item on the feed, then we can skip the whole account
  123. # because none of its statuses would stay on the feed anyway
  124. next if last_status_score < oldest_home_score
  125. end
  126. statuses = target_account.statuses.where(visibility: [:public, :unlisted, :private]).includes(:preloadable_poll, reblog: :account).limit(limit)
  127. crutches = build_crutches(account.id, statuses)
  128. statuses.each do |status|
  129. next if filter_from_home?(status, account.id, crutches)
  130. add_to_feed(:home, account.id, status, aggregate)
  131. end
  132. trim(:home, account.id)
  133. end
  134. end
  135. private
  136. def push_update_required?(timeline_id)
  137. redis.exists?("subscribed:#{timeline_id}")
  138. end
  139. def blocks_or_mutes?(receiver_id, account_ids, context)
  140. Block.where(account_id: receiver_id, target_account_id: account_ids).any? ||
  141. (context == :home ? Mute.where(account_id: receiver_id, target_account_id: account_ids).any? : Mute.where(account_id: receiver_id, target_account_id: account_ids, hide_notifications: true).any?)
  142. end
  143. def filter_from_home?(status, receiver_id, crutches)
  144. return false if receiver_id == status.account_id
  145. return true if status.reply? && (status.in_reply_to_id.nil? || status.in_reply_to_account_id.nil?)
  146. return true if phrase_filtered?(status, receiver_id, :home)
  147. check_for_blocks = crutches[:active_mentions][status.id] || []
  148. check_for_blocks.concat([status.account_id])
  149. if status.reblog?
  150. check_for_blocks.concat([status.reblog.account_id])
  151. check_for_blocks.concat(crutches[:active_mentions][status.reblog_of_id] || [])
  152. end
  153. return true if check_for_blocks.any? { |target_account_id| crutches[:blocking][target_account_id] || crutches[:muting][target_account_id] }
  154. if status.reply? && !status.in_reply_to_account_id.nil? # Filter out if it's a reply
  155. should_filter = !crutches[:following][status.in_reply_to_account_id] # and I'm not following the person it's a reply to
  156. should_filter &&= receiver_id != status.in_reply_to_account_id # and it's not a reply to me
  157. should_filter &&= status.account_id != status.in_reply_to_account_id # and it's not a self-reply
  158. return !!should_filter
  159. elsif status.reblog? # Filter out a reblog
  160. should_filter = crutches[:hiding_reblogs][status.account_id] # if the reblogger's reblogs are suppressed
  161. should_filter ||= crutches[:blocked_by][status.reblog.account_id] # or if the author of the reblogged status is blocking me
  162. should_filter ||= crutches[:domain_blocking][status.reblog.account.domain] # or the author's domain is blocked
  163. return !!should_filter
  164. end
  165. false
  166. end
  167. def filter_from_mentions?(status, receiver_id)
  168. return true if receiver_id == status.account_id
  169. return true if phrase_filtered?(status, receiver_id, :notifications)
  170. # This filter is called from NotifyService, but already after the sender of
  171. # the notification has been checked for mute/block. Therefore, it's not
  172. # necessary to check the author of the toot for mute/block again
  173. check_for_blocks = status.active_mentions.pluck(:account_id)
  174. check_for_blocks.concat([status.in_reply_to_account]) if status.reply? && !status.in_reply_to_account_id.nil?
  175. should_filter = blocks_or_mutes?(receiver_id, check_for_blocks, :mentions) # Filter if it's from someone I blocked, in reply to someone I blocked, or mentioning someone I blocked (or muted)
  176. should_filter ||= (status.account.silenced? && !Follow.where(account_id: receiver_id, target_account_id: status.account_id).exists?) # of if the account is silenced and I'm not following them
  177. should_filter
  178. end
  179. def phrase_filtered?(status, receiver_id, context)
  180. active_filters = Rails.cache.fetch("filters:#{receiver_id}") { CustomFilter.where(account_id: receiver_id).active_irreversible.to_a }.to_a
  181. active_filters.select! { |filter| filter.context.include?(context.to_s) && !filter.expired? }
  182. active_filters.map! do |filter|
  183. if filter.whole_word
  184. sb = filter.phrase =~ /\A[[:word:]]/ ? '\b' : ''
  185. eb = filter.phrase =~ /[[:word:]]\z/ ? '\b' : ''
  186. /(?mix:#{sb}#{Regexp.escape(filter.phrase)}#{eb})/
  187. else
  188. /#{Regexp.escape(filter.phrase)}/i
  189. end
  190. end
  191. return false if active_filters.empty?
  192. combined_regex = active_filters.reduce { |memo, obj| Regexp.union(memo, obj) }
  193. status = status.reblog if status.reblog?
  194. combined_text = [
  195. Formatter.instance.plaintext(status),
  196. status.spoiler_text,
  197. status.preloadable_poll ? status.preloadable_poll.options.join("\n\n") : nil,
  198. status.media_attachments.map(&:description).join("\n\n"),
  199. ].compact.join("\n\n")
  200. !combined_regex.match(combined_text).nil?
  201. end
  202. # Adds a status to an account's feed, returning true if a status was
  203. # added, and false if it was not added to the feed. Note that this is
  204. # an internal helper: callers must call trim or push updates if
  205. # either action is appropriate.
  206. def add_to_feed(timeline_type, account_id, status, aggregate_reblogs = true)
  207. timeline_key = key(timeline_type, account_id)
  208. reblog_key = key(timeline_type, account_id, 'reblogs')
  209. if status.reblog? && (aggregate_reblogs.nil? || aggregate_reblogs)
  210. # If the original status or a reblog of it is within
  211. # REBLOG_FALLOFF statuses from the top, do not re-insert it into
  212. # the feed
  213. rank = redis.zrevrank(timeline_key, status.reblog_of_id)
  214. return false if !rank.nil? && rank < FeedManager::REBLOG_FALLOFF
  215. reblog_rank = redis.zrevrank(reblog_key, status.reblog_of_id)
  216. if reblog_rank.nil?
  217. # This is not something we've already seen reblogged, so we
  218. # can just add it to the feed (and note that we're
  219. # reblogging it).
  220. redis.zadd(timeline_key, status.id, status.id)
  221. redis.zadd(reblog_key, status.id, status.reblog_of_id)
  222. else
  223. # Another reblog of the same status was already in the
  224. # REBLOG_FALLOFF most recent statuses, so we note that this
  225. # is an "extra" reblog, by storing it in reblog_set_key.
  226. reblog_set_key = key(timeline_type, account_id, "reblogs:#{status.reblog_of_id}")
  227. redis.sadd(reblog_set_key, status.id)
  228. return false
  229. end
  230. else
  231. # A reblog may reach earlier than the original status because of the
  232. # delay of the worker deliverying the original status, the late addition
  233. # by merging timelines, and other reasons.
  234. # If such a reblog already exists, just do not re-insert it into the feed.
  235. rank = redis.zrevrank(reblog_key, status.id)
  236. return false unless rank.nil?
  237. redis.zadd(timeline_key, status.id, status.id)
  238. end
  239. true
  240. end
  241. # Removes an individual status from a feed, correctly handling cases
  242. # with reblogs, and returning true if a status was removed. As with
  243. # `add_to_feed`, this does not trigger push updates, so callers must
  244. # do so if appropriate.
  245. def remove_from_feed(timeline_type, account_id, status, aggregate_reblogs = true)
  246. timeline_key = key(timeline_type, account_id)
  247. reblog_key = key(timeline_type, account_id, 'reblogs')
  248. if status.reblog? && (aggregate_reblogs.nil? || aggregate_reblogs)
  249. # 1. If the reblogging status is not in the feed, stop.
  250. status_rank = redis.zrevrank(timeline_key, status.id)
  251. return false if status_rank.nil?
  252. # 2. Remove reblog from set of this status's reblogs.
  253. reblog_set_key = key(timeline_type, account_id, "reblogs:#{status.reblog_of_id}")
  254. redis.srem(reblog_set_key, status.id)
  255. redis.zrem(reblog_key, status.reblog_of_id)
  256. # 3. Re-insert another reblog or original into the feed if one
  257. # remains in the set. We could pick a random element, but this
  258. # set should generally be small, and it seems ideal to show the
  259. # oldest potential such reblog.
  260. other_reblog = redis.smembers(reblog_set_key).map(&:to_i).min
  261. redis.zadd(timeline_key, other_reblog, other_reblog) if other_reblog
  262. redis.zadd(reblog_key, other_reblog, status.reblog_of_id) if other_reblog
  263. # 4. Remove the reblogging status from the feed (as normal)
  264. # (outside conditional)
  265. else
  266. # If the original is getting deleted, no use for reblog references
  267. redis.del(key(timeline_type, account_id, "reblogs:#{status.id}"))
  268. redis.zrem(reblog_key, status.id)
  269. end
  270. redis.zrem(timeline_key, status.id)
  271. end
  272. def build_crutches(receiver_id, statuses)
  273. crutches = {}
  274. crutches[:active_mentions] = Mention.active.where(status_id: statuses.flat_map { |s| [s.id, s.reblog_of_id] }.compact).pluck(:status_id, :account_id).each_with_object({}) { |(id, account_id), mapping| (mapping[id] ||= []).push(account_id) }
  275. check_for_blocks = statuses.flat_map do |s|
  276. arr = crutches[:active_mentions][s.id] || []
  277. arr.concat([s.account_id])
  278. if s.reblog?
  279. arr.concat([s.reblog.account_id])
  280. arr.concat(crutches[:active_mentions][s.reblog_of_id] || [])
  281. end
  282. arr
  283. end
  284. crutches[:following] = Follow.where(account_id: receiver_id, target_account_id: statuses.map(&:in_reply_to_account_id).compact).pluck(:target_account_id).each_with_object({}) { |id, mapping| mapping[id] = true }
  285. crutches[:hiding_reblogs] = Follow.where(account_id: receiver_id, target_account_id: statuses.map { |s| s.account_id if s.reblog? }.compact, show_reblogs: false).pluck(:target_account_id).each_with_object({}) { |id, mapping| mapping[id] = true }
  286. crutches[:blocking] = Block.where(account_id: receiver_id, target_account_id: check_for_blocks).pluck(:target_account_id).each_with_object({}) { |id, mapping| mapping[id] = true }
  287. crutches[:muting] = Mute.where(account_id: receiver_id, target_account_id: check_for_blocks).pluck(:target_account_id).each_with_object({}) { |id, mapping| mapping[id] = true }
  288. crutches[:domain_blocking] = AccountDomainBlock.where(account_id: receiver_id, domain: statuses.map { |s| s.reblog&.account&.domain }.compact).pluck(:domain).each_with_object({}) { |domain, mapping| mapping[domain] = true }
  289. crutches[:blocked_by] = Block.where(target_account_id: receiver_id, account_id: statuses.map { |s| s.reblog&.account_id }.compact).pluck(:account_id).each_with_object({}) { |id, mapping| mapping[id] = true }
  290. crutches
  291. end
  292. end