Opened 6 years ago
Last modified 5 weeks ago
#52345 new defect (bug)
Transient with expiration never expires when storing expiration failed
| Reported by: | mennoll | Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | Awaiting Review |
| Component: | Options, Meta APIs | Version: | 2.8 |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: |
Description
When storing a transient that has a timeout with the set_transient() function, there is a possibility that storing the transient timeout will fail. When you then try to get the transient with the get_transient() function, WordPress just returns it, which basically makes it behave like a transient with no expiration.
You can simulate the behaviour using this code:
<?php // First store the transient $transient_name = 'testname'; $transient_value = 'testvalue'; $transient_expiration = 30; set_transient( $transient_name, $transient_value, $transient_expiration ); // Now delete the transient timeout, simulating the timeout option save failed delete_option( '_transient_timeout_' . $transient_name ); // Now get the transient value var_dump( get_transient( $transient_name ) ); // Returns 'testvalue'
To solve this issue, we need to modify the part in the get_transient() function, that checks if a transient is expired.
The new code of the get_transient() should become this: (see // <=== This is the changed line for what's changed.)
<?php function get_transient( $transient ) { /** * Filters the value of an existing transient before it is retrieved. * * The dynamic portion of the hook name, `$transient`, refers to the transient name. * * Returning a truthy value from the filter will effectively short-circuit retrieval * and return the passed value instead. * * @since 2.8.0 * @since 4.4.0 The `$transient` parameter was added * * @param mixed $pre_transient The default value to return if the transient does not exist. * Any value other than false will short-circuit the retrieval * of the transient, and return that value. * @param string $transient Transient name. */ $pre = apply_filters( "pre_transient_{$transient}", false, $transient ); if ( false !== $pre ) { return $pre; } if ( wp_using_ext_object_cache() ) { $value = wp_cache_get( $transient, 'transient' ); } else { $transient_option = '_transient_' . $transient; if ( ! wp_installing() ) { // If option is not in alloptions, it is not autoloaded and thus has a timeout. $alloptions = wp_load_alloptions(); if ( ! isset( $alloptions[ $transient_option ] ) ) { $transient_timeout = '_transient_timeout_' . $transient; $timeout = get_option( $transient_timeout ); if ( false === $timeout || ( false !== $timeout && $timeout < time() ) ) { // <=== This is the changed line delete_option( $transient_option ); delete_option( $transient_timeout ); $value = false; } } } if ( ! isset( $value ) ) { $value = get_option( $transient_option ); } } /** * Filters an existing transient's value. * * The dynamic portion of the hook name, `$transient`, refers to the transient name. * * @since 2.8.0 * @since 4.4.0 The `$transient` parameter was added * * @param mixed $value Value of transient. * @param string $transient Transient name. */ return apply_filters( "transient_{$transient}", $value, $transient ); }
Change History (11)
#1
@
6 years ago
- Summary Transient with expiration never expires → Transient with expiration never expires when storing expiration failed
This ticket was mentioned in PR #910 on WordPress/wordpress-develop by menno-ll.
6 years ago
#2
- Keywords has-patch added; needs-patch removed
#5
@
6 years ago
- Keywords needs-refresh added
- Version 5.6 → 2.8
For transients set without a timeout (ie, the $expriation parameter in set_transient() is zero or another falsy value) the timeout option is not set. This means the above approach would end up deleting permanent transients when getting them.
For expiring transients, an alternative approach would be a similar approach in set_transient(): if the transient value option is saved successfully but the timeout option fails to save then the value is deleted.
In very simplified code:
<?php $timeout_result = add_option( $transient_timeout, time() + $expiration, '', 'no' ); if ( $timeout_result ) { $result = add_option( $transient_option, $value, '', 'no' ); if ( ! $result ) { // delete both options. } }
Due to the way set_transient() works, the simplified code would need to be repeated a couple of times and some modification for the calls to update_option() as it will return false if the new value matches the old.
This seems like a pretty edge-case bug so I am not sure if the additional code provides much benefit, is it something you have hit frequently?
It looks like this has been the case since transients where first introduced in 2.8, so I've updated the version to reflect that.
#6
@
6 years ago
Hi Peter, thank you for the response. To first reply to the last question you asked: yes, i've encountered this issue a few times now, in multiple websites. From testing, it looks like getting transients is going well, except for when a transient is not requested for some time. It looks like some garbage collection feature is deleting the transient timeout value from the database. I was not able to see where that went wrong, so I was not able to detect if that's a problem in WordPress Core, or in a plugin. I searched in my plugins but there was no code to be found that could interfear with how transiens work. Therefore it could be in core, but looking in code, I could not find the immediate problem.
However, like you can see, I was able to modify the get_transient() function to let it work correctly.
I see you are worried about that my solution might break transients that don't have a timeout. But I do think that this is not true. The code change I made is inside the if statement, that checks if a transient should have a timeout: (see this code below). Therefore I think this change only applies to transients that do have a timeout.
<?php // If option is not in alloptions, it is not autoloaded and thus has a timeout. $alloptions = wp_load_alloptions(); if ( ! isset( $alloptions[ $transient_option ] ) ) { // Code is here }
I am indeed high aware of the issue that you pointed out in the Github PR, and how we could possibly fix my experienced bug via the get_transient() function. Unfortunately, I do also think that's not the full solution. I do think, we actually need both your suggestion, and mine.
To be even more clear, I do think that if I read trac ticket WP#30380, that the ticket is actually outdated. I fully understand that they wanted to save a few queries here because they seemed useless. But I think their unit test is not valid anymore.
We can however still pass their unit test, and also have a solution. If I change my code so that the transient will not be deleted, but the get_transient() still returns false, all unit tests should succeed.
To summarize, I think we need to discuss a little about the correct solution, and am happy to do so. Could you please give your opinion about the following list of questions:? Thanks :)
- I think that my change does not affect permanent transients. Could you please explain how you think it will?
- What do you think about both having a check in
get_transient(), and your suggestion inset_transient()? - I have doubt if i think the trac ticket 30380 is still valid, and therefore would like to know if you think that in my code deleting the transient there is the way to go (which requires that unit test to be deleted)
Thank you, hope to hear from you soon.
#7
@
4 years ago
Hi @peterwilsoncc ,
I would like to let you know that I've implemented your suggested modifications.
And I've also changed the included unit test.
It now actually actively simulates the actual cause of the problem, which was the failure of a database query.
I hope to hear if this is more what you had in mind!
Thanks in advance.
#9
@
3 years ago
Hi all,
Last year I've changed my Pull Request dunging the contributor day at WordCamp Europe 2022 to implement the changes requested.
And in about two days, another contributor day is happening at WCEU 2023 :).
I however see that my PR has not been yet reviewed, and I would like to know if there are changes to be made still. If there are, I would like to make the changes during contributor day at the Core table, but otherwise I might want to see if I can help on another department as well. Please let me know if able ;).
Kind regards, Menno
This ticket was mentioned in PR #14340 on WordPress/wordpress-develop by @dhrupo.
5 weeks ago
#10
Refreshes the approach from #910 by @menno-ll (now conflicting with trunk), following @peterwilsoncc's suggestion in comment:5 on the ticket.
Summary
When set_transient() creates a transient with an expiration, it writes two rows: _transient_timeout_{name} and _transient_{name}. On the "add" paths the result of writing the timeout row was ignored, so if the database rejected that INSERT the value was still stored. With no timeout row, get_transient() returns the value forever. set_site_transient() has the same pattern. sukhendu2002 confirmed the behaviour on trunk in #44977 (comment:5).
Fix
On the add paths, the value is now only stored when the timeout row was written or already exists:
$result = add_option( $transient_timeout, time() + $expiration, '', false ) || '' === $wpdb->last_error || false !== get_option( $transient_timeout );
add_option() returning false is not enough on its own to mean "failed":
- Concurrent requests. It uses
INSERT … ON DUPLICATE KEY UPDATE. If another request wrote the same timeout in the same second, MySQL reports 0 changed rows andadd_option()returnsfalse. The cache primed at the start ofset_transient()still says the row is missing, so only the database error tells a real failure apart.wpdb::query()resetslast_errorbefore every query. - Orphaned timeout rows, for example when only the value row was deleted.
add_option()returnsfalsewithout querying, and these keep today's behaviour through theget_option()check.
The same rule applies to the branch that adds an expiration to an existing transient without a timeout, and to set_site_transient().
The update paths, where a timeout row already exists, are unchanged. A failed update there still leaves an expiry in place. It also avoids a trap in #910: update_option() returns false when the value is unchanged, so treating that as a failure drops a second set_transient() with the same expiry in the same second.
Testing
New tests (@ticket 52345) in Tests_Option_Transient and Tests_Option_SiteTransient. The database failure is simulated by pointing only the timeout INSERT at a missing table, so wpdb reports a real error, and a concurrent write by replaying the same INSERT from the query filter.
| Case | trunk | this PR |
|---|---|---|
| Timeout INSERT fails, new transient (and site transient) | value stored with no timeout ❌ | false, nothing stored
|
| Timeout INSERT fails while adding an expiry to an existing transient | value stored with no timeout ❌ | false
|
| Same transient set twice in a second with the same expiry | latest value ✅ | latest value ✅ |
| Orphaned timeout row | stored ✅ | stored ✅ |
| Timeout written concurrently by another request (both branches; site transient) | stored ✅ | stored ✅ |
The 3 failure cases fail on trunk; all 9 pass with this change, on single site and multisite:
./vendor/bin/phpunit --group 52345 OK (9 tests, 24 assertions) ./vendor/bin/phpunit -c tests/phpunit/multisite.xml --group 52345 OK (9 tests, 24 assertions) ./vendor/bin/phpunit --group option Tests: 451, Assertions: 1118, Warnings: 1, Skipped: 3 ./vendor/bin/phpunit -c tests/phpunit/multisite.xml --group option Tests: 486, Assertions: 1232, Warnings: 1, Skipped: 3
The one warning is an existing PHPUnit 10 deprecation notice in Tests_Option_wpUserSettings.
Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Tracing the transient write paths, writing the fix and tests, and reviewing it for regressions (two review passes found the concurrent-request case, which is now covered by tests). All changes were reviewed by me.
#11
@
5 weeks ago
PR https://github.com/WordPress/wordpress-develop/pull/14340 refreshes the approach from the earlier PR by @mennoll (which now has merge conflicts with trunk), following comment:5. @mennoll, I've kept you in the props; happy to hand it back if you'd like to continue.
On the add paths of set_transient() and set_site_transient(), the value is now only stored when the timeout row was written or already exists. Two details came up while testing:
add_option()usesINSERT … ON DUPLICATE KEY UPDATE, so when a concurrent request writes the same timeout in the same second it returnsfalsewithout an error. The patch only treats the write as failed when$wpdb->last_erroris set, so concurrent requests and orphaned timeout rows keep today's behaviour.- The update paths are unchanged.
update_option()returnsfalsefor an unchanged value, so treating that as a failure (as the earlier PR did) would drop a second write with the same expiry in the same second.
Tests cover a real failed INSERT, the existing-transient branch, site transients, the same-second double write, orphaned timeout rows, and concurrent writes. The 3 failure cases fail on trunk; all 9 pass on single site and multisite, and the option group passes.
#44977 looks like a duplicate of this ticket.
AI disclosure: I used Claude Code to help trace the code, write the patch and tests, and review it. I reviewed all of it.
When getting an existing transient that should have a timeout, but in reality it has not, delete the existing transient and return false.
Trac ticket: https://core.trac.wordpress.org/ticket/52345