Repository navigation
Closed
Labels
Issue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifIssue-Enhancementthe issue is more of a feature request than a bugResolution-FixedThe issue is fixed.WG-Languageparser, language semantics
Milestone
Description
Was discussing with Jeffrey Snover (@jpsnover) a concern that if a cmdlet opens a resource (like a database connection) in Begin, and later in the pipeline an exception is thrown, End is not called to dispose of the connection.
Steps to reproduce
function a {
[cmdletbinding()]
param()
begin { "a:begin" }
process { 1 }
end { "a:end" }
}
function b {
[cmdletbinding()]
param([parameter(ValueFromPipeline=$true)]$a)
begin { "b:begin" }
process { $a; throw 'oops' }
}
a | bExpected behavior
b:begin
a:begin
a:end
oops
At /Users/steve/test/end_not_called.ps1:15 char:19
+ process { $a; throw "oops" }
+ ~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (oops:String) [], RuntimeException
+ FullyQualifiedErrorId : oops
Actual behavior
b:begin
a:begin
oops
At /Users/steve/test/end_not_called.ps1:15 char:19
+ process { $a; throw "oops" }
+ ~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (oops:String) [], RuntimeException
+ FullyQualifiedErrorId : oops
Environment data
Name Value
---- -----
PSVersion 6.1.0-preview.1
PSEdition Core
GitCommitId v6.1.0-preview.1
OS Darwin 17.5.0 Darwin Kernel Version 17.5.0: Mon Mar 5 22:24:32 PST 2018; root:xnu-4570.51.1~1/RELEASE_X86_64
Platform Unix
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0Reacted by Mark Kraus, Troy Campbell, Kris Borowinski, mi-hol, Paulo Morgado, Rain Sallow (/u/ta11ow), aetos, Peter Vandivier, Luc FULLENWARTH, Carlo Cardella and 3 more
Metadata
Metadata
Assignees
Labels
Issue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifIssue-Enhancementthe issue is more of a feature request than a bugResolution-FixedThe issue is fixed.WG-Languageparser, language semantics
Activity
BrucePay commentedon Apr 18, 2018
Steve Lee (@SteveL-MSFT) I had some further discussions with Jeffrey Snover (@jpsnover). Basically EndProcessing isn't called if there is an exception because it's not a destructor. EndProcessing is just part of the normal processing. Consider a counter function
function count {begin {$c=0} process {$c++} end {$c}}. An exception should terminate function execution not resume execution atend. If it ranendthen whatever was in$cwould be incorrectly emitted to the pipeline. As far as clean-up goes, for compiled cmdlets, we callDisposeon the cmdlet which allows for clean-up. For scripts, we don't exposeDisposein a useful way so perhaps we should add a "cleanup { }" block for functions scripts. (IIRC our thinking wrt scripts was that scripts call cmdlets and cmdlets get disposed therefore most things in a script will be disposed. Things that don't get disposed that way will eventually be disposed by the garbage collector/finalizer q.e.d there was no need for a cleanup block.)SteveL-MSFT commentedon Apr 18, 2018
Seems reasonable
dragonwolf83 commentedon Apr 18, 2018
I don't like the idea of waiting on garbage collection to close a database connection. There is a need for a
Cleanup {}orFinally {}block for the exact scenario outlined.I wrote an "advanced function" that opens a
DataReaderconnection in theBegin {}block so that it could pass the record to other cmdlets to do stuff. I could never figure out how to properly close it if a terminating error happened anywhere in the pipeline. Adding a new block would solve that problem.iSazonov commentedon Apr 19, 2018
Interesting how cmdlet dispose local variables? We could add a script property (or something like that) with code to mandatory execute a dispose code.
SteveL-MSFT commentedon Apr 19, 2018
Reusing this issue to consider having a
Finally{}type block for cleanup[-]EndProcessing is not called if exception is thrown in pipeline[/-][+]Add new `finally {}` type block so script cmdlets have opportunity to cleanup[/+]aetos382 commentedon Apr 19, 2018
Please consider providing syntax like C# using block.
PetSerAl commentedon Apr 19, 2018
Ilya (@iSazonov)
Compiled cmdlets can just implement
IDisposableand PowerShell engine properly call it to do cleanup.iSazonov commentedon Apr 19, 2018
I meant
BrucePay commentedon Apr 20, 2018
aetos (@aetos382) This is a slightly different scenario where a resource internal to the command is opened in
Begin, used inProcessand then closed inEnd. Ausing-style statement isn't applicable since there are three separate blocks and you don't want to dispose the resource when a block completes, only when all blocks have completed. Now you could wrap each of the blocks in atry/catchstatementNote that you want to use
catchinstead offinallybecause you only want to close the resource if there's an exception. In the normal flow, the resource would be released in theendblock.WRT the
finally {}cmdlet block Steve Lee (@SteveL-MSFT), proposes, I expect that it would be run when the command is disposed by the pipeline processor. (Consequently, one might argue that it should be calledDisposeinstead ofFinally. Another name might betrap { }in which case we would have to think aboutbreakandcontinuesemantics.[-]Add new `finally {}` type block so script cmdlets have opportunity to cleanup[/-][+]Add new `Dispose {}` type block so script cmdlets have opportunity to cleanup[/+]49 remaining items
iSazonov commentedon May 13, 2020
The idea was expressed by Bruce Payette (@BrucePay), then in another form Jason Shirk (@lzybkr), then alx9r.
I would not want to lose this idea and put it in PowerShell/PowerShell-RFC#250
vexx32 commentedon May 13, 2020
Ilya (@iSazonov) appreciate the writeup!
I had a bit of a read just a little bit ago, but it seems to me the concept is flawed from the beginning. Automatic resource management is effectively trying to predict what users want from the code, which IMO is never a great way to try to create a reliable experience for users.
I'll add more detailed comments to the RFC itself.
iSazonov commentedon May 13, 2020
Rain Sallow (/u/ta11ow) (@vexx32) The RFC comes from the fact that I like when PowerShell makes smart things :-)
As joke - it seems to you :-) Do you really deny the garbage collector in C#?!
vexx32 commentedon May 13, 2020
Not at all. But I think us attempting to re-create a garbage collector when there's already one available in .NET is a bit of wasted effort, frankly. Can we improve how we work with it? To a point, sure! But trying to do too much there is liable to create an incredibly confusing UX.
iSazonov commentedon May 13, 2020
We need to look script examples where it could be a problem.
essentialexch commentedon May 13, 2020
There is nothing that says both of these cannot be done.
I'd really (speaking as someone who prefers language to change slowly!!) prefer to not wait another year or two to have a dispose-type capability in PowerShell. It's an enormously powerful concept especially for network, database, and file-system (i.e., most) scripts that are long-running and robust.
So I'd hate for Rain Sallow (/u/ta11ow) (@vexx32) 's implementation to get derailed by a similar-but-not-identical resource-tracking proposal from Ilya (@iSazonov) .
SeeminglyScience commentedon May 13, 2020
I don't necessarily see a problem with scope based disposal, but it's gotta be explicit. For instance, a nested/non-public function that creates a database connection for use in a larger function/module is gonna break.
iSazonov commentedon May 13, 2020
It is developer duty to make this correctly. If it is a module developer should set "DisposeKind.AtModuleUnload" for the connection object. Now consumer gets PowerShell magic - automatically closing the connection.
I would not want us to dive into the implementation details - it is clear that this is not easy.
vexx32 commentedon May 13, 2020
Yeah, I'm not sure I see a lot of value in making this a "magic" sort of implementation. If there is desire for that kind of functionality on module unload, authors can already register tasks for module unload. I wonder if we'd be perhaps better off making that functionality more easily accessible in general rather than for a specific targeted purpose you're suggesting..
SeeminglyScience commentedon May 13, 2020
If I do this:
How am I as a script writer supposed to know that
$rsis now closed. Even as someone who would be well aware of the change, it would be incredibly difficult to troubleshoot.Plus, you can assign objects you don't own to variables:
Yeah psuedo code is fine of course. To be clear though, if automatic disposal is opt-out then this would be an incredibly large breaking change.
iSazonov commentedon May 13, 2020
I believe PowerShell can be smart enough to understand that an object is published in pipeline and shouldn't be destroyed. Can? :-) It is mentioned in RFC too. In fact, we can come up with any scenario and find a way to get around it or vice versa to fix it.
SeeminglyScience commentedon May 13, 2020
It's not going to be that easy, you'd need full escape analysis
Plus you'd have to intimately familiar with all of those restrictions, if not then troubleshooting why your object breaks in script A but works great in script B will be very difficult.
I don't see why it has to be automatic. Adding another use to the
usingkeyword for assignments alausing $b = [runspacefactory]::CreateRunspace()seems like the move to me. If you don't explicitly request disposal, waiting until it hits the finalizer is probably fine. If not, it's the developers duty to quickly mark the assignment withusing.jborean93 commentedon Feb 13, 2022
I believe this was implemented with #15177, feel free to correct me if I'm wrong.