/
Session Typing for a Featherweight Erlang Dimitris Mos Session Typing for a Featherweight Erlang Dimitris Mos

Session Typing for a Featherweight Erlang Dimitris Mos - PDF document

tatyana-admore
tatyana-admore . @tatyana-admore
Follow
402 views
Uploaded On 2015-06-17

Session Typing for a Featherweight Erlang Dimitris Mos - PPT Presentation

Vasconcelos LaSIGE Faculty of Sciences University of Lisbon Abstract As software tends to be increasingly concurrent the paradigm of message passing is becoming more prominent in computing The language Erlang o64256ers an intuitive and industryteste ID: 87919

Vasconcelos LaSIGE Faculty

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "Session Typing for a Featherweight Erlan..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

withoutreferencesitisdiculttoensuremessagecorrelationevenforsimplerequest{response:usingjustprocessidentity(e.g.,theuniquemailboxofthesender)isnotenough,asanyprocesscan\impersonate"anotherjustbyknowingitsidentitywhichitcanattachtoamessage[2].Thus,make ref()seemstobetheonlymeansto\getconcurrencyright."Yet,anad-hocuseofmake ref()mayleadtoapplicationsthatsu erfrominterference,raceconditions,oreventhatfailfromdeliveringtheexpectedresults.Oursystemprovidesforamethodologythatgovernsitsuse,whilestaticallyguaranteeingthatprogramsbehaveaccordingtotheplan.Wehaveonlyaddressedatinypartofthelanguage,alanguagethatisuntypedinnature.ScalingourproposaltoalargersubsetofErlangconstitutesaninterestingchallenge.Moreover,ourcontributioncanbeviewedalsoasatypesystemforanimportantpatternofconcurrentbehavior,apatternthatgoeswellbeyondwhatconventionalsessiontypescurrentlyallow,whilepresentingideasthatmaybeincorporatedinfuturemessagepassing,bu ered,concurrentlanguageswherereceiversmayinspectamailboxpickingappropriatemessages.CoreErlang[4],acanonicalformatforErlangprograms,isusedinternallybytheErlangcompiler,andalsobymanyveri cationtools,mostnotablyDia-lyzerwhichispartoftheErlangdistribution.DialyzerdetectserrorsbyinferingtypesbasedonSuccessTypings[9].However,untilnowthetype-basedmethodsdevelopedforErlangfocusentirelyonthefunctionalpartofthelanguage,andarethereforeirrelevantinverifyingthepropertiesofconcurrentmessage-passingprograms.Morerecently,in[5],ananalysismethodwasimplementedthatcanstaticallydetectde nitecommunicationerrorsinErlangprograms,basedonatopologicalsynthesisofcommunicationprimitiveusages.Suchpropertiesincludethecasewheresentmessagescannotbematchedbyareceive,however,ithasadi er-entapproachthanours:itdoesnotcheckprogramsagainsttypes,butratheranalysesthemagainsteachother,detectingundesirablecompositionsofsend-ingandreceiving.Ontheotherhand,thismethodisautomatedandhasbeenimplementedontopoftheDialyzertool.Therestofthepaperisstructuredasfollows.Thenextsectionpresentsourlanguageviaanexample.Then,Section3formallyintroducesthesyntaxandreductionsemanticsofthelanguage.Section4presentsthetypeassignmentsystemanditsmainresults.Section5concludesthepaper.2AmotivatingexampleConsidertheclassicalreaders-writerproblem.Agivenresourcecanbewrittenby(exactly)onewriterwhennoreadersarereading;itcanbesimultaneouslyreadbyaboundednumberorreaderswhilenowriteriswriting.Acontrollerprotectingaccessestosucharesourceprovidesfortwodistinctoperations(orservices):readandwrite.Giventheconstraintsenumeratedabove,eachoftheseservicesisassociatedwithalittleprotocol.Uponinvokingservicewrite,writersreceiveoneoftwomessages:welcomemeaningthatnoreaderisreading,orreadingmeaningthereisatleastone Inthe rstlinethemonitorreceivesamessagewithtworeferencesandusesthesecond,Y,forlettingthewriterknowtowhichsessiondoesthewelcomemessagebelongto.Thewriter,inturn,usesthe rstreference,X,to`sign'thesubsequentmessagesinthesession.Inthewritephase,themonitormayacceptmessagesfromthejustinitiatedsession(weomittheactualdatatobestoredattheresource).write(X)=receivefstore,Xg!idle().Duringthisphase,readersinvokingthereadservicewouldblockwaitingfortheservertogobacktotheidlestate.Ourlanguageallowsformorethanthis:theservermayaswellanswerimmediatelytoclients(withawritingmessage),whilewaitingfromthewriter'sstoremessage.Thatis,ourserverisabletoinitiatenewserviceswhilerunningotherservices.write(X)=receivefstore,Xg!idle();fread, ,Z,Readerg!Reader!fwriting,Zg,write(X).Thecodeforthereadphaseshouldbynowbeeasytounderstand;forsimplic-ityweallowtwosimultaneousreaders,max.Andweneverleaveaclientwithoutananswer.readOne(X1)=receivefload,X1g!idle();fwrite, ,Z,Writerg!Writer!freading,Zg,readOne(X);fread,X2,Y2,Reader2g!Reader2!fwelcome,Y2g,readTwo(X1,X2).readTwo(X1,X2)=receivefload,X1g!readOne(X2);fload,X2g!readOne(X1);fwrite, ,Z,Writerg!Writer!freading,Zg,readTwo(X1,X2);fread, ,Z,Readerg!Reader!ffull,Zg;readTwo(X1,X2).InthereadTwophasewedecidedtohonorallpossiblecases:continuingwiththetwoopensessionswithbothreaders,openingnewsessionswithnewreadersandwriters.Butthatneednotbethecase,atanymomentprogrammersmaychoosewhichsessionstocontinueandwhichnewservicerequeststoaccept.Tocompleteourexamplewewritethecodeforareaderthattriestostoreattheresource(andgivesupifunable).reader()=make refX,Yforself,ResourceinResource!fread,X,Y,selfg,receivefwelcome,Yg!Resource!fload,Xg;fwriting,Yg!;ffull,Yg!.Forconvenience,wecreatepairsoffreshreferencesinonestepwithamake refoperation.Thethuscreatedreferences,XandY,mustbeboundtothepidoftheprocessesthatwillengageininteraction.Themonitor,withpidResource,isgoingtouseXforreadingandYforwriting.Symmetrically,thecurrentwriter(withpidself)willuseYforreadingandXforwriting.Whatguaranteesdoweobtainfromourtypesystem?Todiscussthismat-terwemustrememberthat,inErlang,messagesendingisnon-blockingandthatmessagesmayberetrievedfromthemailboxinanyorder(asopposedto, identi ertovariableXandcontinueswithtermQ.Finally,atermoftheformmake refX;Yforu;vinPcreatestwouniquereferences,bindsthemtovariablesXandY,associatesthemtoprocessidenti ersuandv,andcontinueswithtermP.Asimpleformoftermsallowingthedescriptionofunboundedbehaviour,e.g.defA~X=PinPandA~V,canbeeasilyincorporatedinourlanguage,fol-lowing,e.g.,[7,12].Forthesakeofsimplicity,andinordertoconcentrateonthenovelaspectsofoursystem,wedecidednottoincludethem.Fortheruntimelanguageweneedtwonewclassesofidenti ers:processidenti ers(pid's)denotedby anduniquereferencesdenotedbyr.Thesyntaxoftermsremainsunchanged,exceptfortheextendedcategoryofidenti ers.Termsdonotengageinreductionperse.Insteadtheymustbeuploadedintoacon guration.Con gurationsarebuiltfrom vedi erentconstructors.Atermoftheform :~Mdescribesamailboxfortheprocesswithpid ,containingalistof(unread)messages~M;aprocess [P]isatermPlocatedatpid .Thenwehavescoperestrictionoperators,( )Cforprocessidenti ers,and(r 11r 22)Cforpairsofreferences.Finally,con gurationsoftheformC1jC2allowC1andC2toruninparallel.Wecountwiththreebindersfortermsandtwoforcon gurations.Theyare:thevariables~Xinareceivepatternf~Xgwhen~Y=~u,variableXinaspawntermspawnPasXinQ,variablesX1andX2(butnotu1andu2)inarefer-encecreationtermmake refX1;X2foru1;u2inP,processidenti er incon g-uration( )C,andreferencesr1andr2(butnot 1and 2)incon guration(r 11r 22)C.Inordertosimplifythesubsequentpresentationweuseletternforanyofthebinders orr 11r 22.Thesetsoffreevariablesandboundvariablesarede nedaccordingly.WefollowBarendregt'svariableconvention,requiringboundidenti erstobedistinctfromfreeidenti ersinanymathematicalcon-text.Asubstitutionisamap( nite,partialdomain)fromvariablesintovalues,writtenf~V=~Xgandrangedoverby.The(capturefree)operationofapplyingasubstitutiontotermP,denotedP,isstandard.IfPisaprogram(aclosedterm),weuploadPatourmachinebybuildingacon gurationoftheform( )( [Pf =selfg]j :")composedofprogramPlocatedatprocessidenti er ,andemptymailboxforthesamepid("denotestheemptysequence).ThedistinguishednatureofvariableselfisapparentinPf =selfg:processPmayrefertoitsownpidviaself,whichatruntimeisreplacedbytheactualvalue .StructuralcongruenceisthesmallestrelationonprocessesincludingtherulesinFigure2.The rsttworulessaythatparallelcompositioniscommutativeandassociative.Therulesinthesecondlinedealwithscoperestriction.The rst,scopeextrusion,allowsthescopeofntoencompassC2;duetothevariableconvention,nboundin(n2)C1,cannotbefreeinC2.Theothertworulesallowexchangingtheorderofrestrictions.1 1Noticethat(r 11r 22)( 1)C6( 1)(r 11r 22)Cduetothevariableconvention(theleft-handsidecon gurationisnotwellformed). 1[ 2!M;P]j 2:~M�! 1[P]j 2:~MM(send)j2Imatch(pj;M)=match(pi;M0)unde ned8i2I;8M02~M1 :~M1M~M2j [receivepi!Pii2I]�! :~M1~M2j [Pj](recv) [make refX1;X2for 1; 2inP]�!(r 11r 22) [Pfr1r2=X1X2g](mkref) 1[spawnPasXinQ]�!( 2)( 1[Qf 2=Xg]j 2[Pf 2=selfg]j 2:)(spawn)C1�!C2 C1jC3�!C2jC3C1�!C2 (n)C1�!(n)C2C1C2�!C3C4 C1�!C4(par;res;str) Fig.4.Reductionby 2,andthe(empty)queue 2:.ThenewlycreatedpidisreplacedinthecontinuationprocessQ,sothatQmaythencommunicatewiththenewprocess.Whatcangowrongwithourmachine?Lookingattheoperationalsemantics(Figure4)nothing,really.Sendalwayssucceeds(forweadmitmailboxbu erstobeunbounded);receivemaynotsucceed(fortworeasons:nomessageinmailbox,nomessageinthemailboxmatchesthepatterns)butthatdoesnotconstituteanabnormalbehaviour; nally,thereisnoreasonwhymake refandspawnshouldnotsucceed.Thepossibleabnormalconditionshavetodowithourunderstandingofhowsessionsmusthappen.Weidentifytwocases:aprocessterminates(reducestoavalue)butleavessessionmessagesinthemailbox;aprocesstriestoreceiveamessagewithagivenlabelwithinagivensessionbut ndsnosuchmessageinthemailbox.Fortheformercaseandgiventheasynchronousnatureofouroperationalsemantics,onemaystill nd,atterminationandinthemailbox,asessioninitiationmessagefollowedbysessionmessages.Thisdoesconstituteamalfunctioningsincethesessionwasneverstartedontheserverside.Inthelattercase,processesneednotreceivemessagesforallopensessionsatalltimes,butiftheydecidetoreceiveamessageonagivensession,thentheymustcontainpatternsforallpossiblemessagesinthatsession(otherwiseoneorbothoftheparticipantscangetstuckbybeingunabletoreceivethenextmessage).Wethensaythatacon gurationCconstitutesanerrorwhenCisstructuralcongruentto(~n)( [P]j :~MjC0)andIncompletesession:termPisavalue,bu er~Misoftheform~M1f ;X; g~M2,andnomessagein~M1isoftheformf ; ;X; g,orUnmatchedsessionmessage:termPisreceive(fX;Y; gwhenX;Y=a;r!Q;:::),thereisonemessagein~Moftheformf ;r; gbutnomessageoftheformfa;r; g.Thetypesysteminthenextsection ltersoutsuchabnormalcases. �;u:T;f(ui;wippi):endgi2I` u:T�;f(ui;wippi):endgi2I` a:atom(identi er,atom)�; ` p:fai:Sigi2I�;;(u2;u1pp): Sj`uP:Tj2I �;;(up1;uu2):ref`up!faj;u1;u2;ug;P:T(request)�; ` V:Tj�;;(u1;u2pp):Sj`uP:Tj2I �;;(u1;u2pp):[ai:Ti!Si]i2I`up!faj;u2;Vg;P:T(out)�;`accupi!Pi:T�;`inuqj!Qj:T8i2I;j2Jconsistent(;(qj)j2J) �;`ureceive(pi!Pi)i2I;(qj!Qj)j2J:T(receive)�; ` u:fai:Sigi2I�;;(X1;X2pp):Sj`uPfaj=Xag:Tj2I �;`accufXa;X1;X2;pgwhenXa=aj!P:T(accept)�;Y:Tj;;(u1;u2pp):Sj`uPfaju1=XaXg:Tj2I �;;(u1;u2pp):&[ai:Ti!Si]i2I`inufXa;X;YgwhenXaX=aju1!P:T(in)�;X:T;1`XPfX=selfg: �;X:T;2`uQ:T �;1;2`uspawnPasXinQ:T(spawn)�;;(Xu;Yv):ref`uP:T �;`umake refX;Yforu;vinP:T(mkref) Fig.6.Typingrulesfortermstheprocessonpknowshowtostartanajsession,read(andremove)thepairofreferencesu1;u2fromandaddanewsession-entryto.Thenewentryrecordsthetworeferences,thepidofthetargetprocessandthedual(sinceweareontheclientside)ofthesessiontypeforsessionaj.Inthelattercasewearewithinasession:wetypecheckthecontinuationtermPtoobtainatypeSjforthesessionpertainingtou2(thewritereference)andbuildatypeaccordingly.Theruleforreceiveisthemostcomplexonefortheremaybemultiplebranches,sometryingtoopennewsessions,otherstryingtoprogressonalreadyopensessions.Weassumethebranchespartitionedintwosets:thoseopeningnewsessionsandthoseengagedinopensessions.Fortheformerweuseruleacceptwhichshouldbeconfrontedwithrulerequest.ThistimeweuseSjbe-causeweareontheserverside;wealsopropagatethee ectofpatternmatchingonthecontinuationprocessP,viaanappropriatesubstitution.Forthelatterweuseruleinwhichshouldbeconfrontedwithruleout:weplaceanentryformessagepayloadYinthesharedenvironmentandpropagatethesubstitutionasinaccept;forthetypeofthesession,weusea&type,ratherthanatype.Intheruleforreceiveallbranchesmusthavethesamelinearcontext.Butthisisnotenough,forinruleinwe`guess'fromonelabelajthewholesetoflabelsinareceivesessiontype.Wemustthenmakesurethatwedonotdeclareinthetypelabelsthatarenotinthereceivepattern.Predicateconsistentisusedforthee ect.Wesaythatcontextisconsistentwithasetofpatterns �;` P: �;` [P]�;1`C1�;2`C2 �;1;2`C1jC2(process;par)�; :T;; :~`C �;`( )C�;i` Mi:i8i21:::n �;1;:::;n; :1:::n` :M1:::Mn(newpid;mbox)�;;` :fai:Sigi2Ij2I �;f(r1;r2p 0):Sjg` faj;r1;r2; 0g:req�;;` V:T �;;` fa;r;Vg:a(T)@r(reqmsg;sesmsg)�;;(r 11;r 22):ref`C �;`(r 11r 22)C 1:~1; 2:~22S1�(~1r1)= S2�(~2r2)�;;(r1;r2p 2):S1;(r2;r1p 1):S2`C �;`(r 11r 22)C(sesrefs;newrefs) Fig.7.Typingrulesforcon gurationssharedenvironment,exposingatypeforincomingrequests,andwealsoexpectinthelinearenvironmentsomeentry :~forthecorrespondingmailbox.Rulemboxwhichtypeseachmessageinthemailboxof andcomposesthelinearenvironmentstogetherwithasequenceofmessagetypesfor .Inturn,wecanexaminethemessagetypingrulesreqmsgandsesmsg.Inreqmsgtherequestmessageintroduces,inthelinearenvironment,theusagethattheprocessreceivingthemessagewouldperform,whichisneededtomatchthesymmetric(dual)usageobtainedwithrulerequestofFigure6.Observethatthegiventypereqdoesnotneedtocarryadditionalinformation.Theninsesmsgasessionmessageisgivenatypea(T)@r;asequenceofsuchmessagetypescaninformaboutthemessagesofasessionthatarealreadyinthemailbox,andisusedtoobtainthecorrectremainingusage(modulothesemessages)persession.Rulenewrefsisforwhenapairofreferenceshasbeencreated,butasessionrequestmessagehasnotbeensentyet.Itfacilitatesasubsequentuseofrulerequest.Rulesesrefsensuresthatsessionsaredual.Toobtaintheactualsessiontypethatremainstobeperformedoneachsideofasession,wecarefullyadvancethesessiontypesSiofeachsessionpartneraccordingtothetypesofmessagesalreadyreceived.Toachievethis,weutilisetwoauxiliaryde nitions.First,wewanttoextractfromamailboxthemessagetypeinformationthatpertainstothespeci creferenceriusedforinput;forthisweuse(iri)de nedas:req~r=~ra(T)@r~r=a(T)(~r)a(T)@r0~r=~rifr6=r0whichgeneratesasequence(written~)ofmessagepre-typesa(T)strippedofreferenceinformation.Then,weadvanceeachsessiontypeSibycalculatingthesessionremainderS0igivenfromSi�i=S0i.Theremainderisde nedas:S�=S&[ai:Ti!Si]i2I�aj(Tj)~=Sj�~ifj2I[ai:Ti!Si]i2I�~=[ai:Ti!Si]i2I mentioningrinaterminatedprocess [V]willbeend,andthemailboxwillhaveanon-emptysetofsessionmessagesonrnotprecededbyacorrespondingrequestmessage(withinputreferencer);thereforethesessionremainderwillbeunde ned.Inthecaseofunmatchedmessages,wecanshowthatacon gurationinwhichamailboxcontainsamessagecarryingrtogetherwithanatomthatisnotsupportedinthereceivingprocessisuntypable,sinceagainthemessageremainderwillbeunde ned.Inbothcasesanapplicationofsesrefswillfail.Thereareotherundesirablecon gurations,namelywhenthesamereferenceappearsinmessagesoccurringinparallelthreads(causingnon-determinisminthereceivingorder),orwhensubsequent(orparallel)requestssharesomeref-erence.However,suchcon gurationsaretriviallyuntypable,sincethelinearenvironmentscomposedinthesecasesareunde ned.5FurtherworkSomeErlangprogramsconsistofsimplemessageexchangesanddonotrequireprovisionsforsessions,inparticulartheuseofreferences.Wecaneasilyadaptoursystemtohandlethesecasesbyextendingpidtypestofai:Si;bj:Tjgi2I;j2Jallowingaprocesstoreceivesimplemessagessuchasfb;Vg.Then,receivepat-ternsoftheshapefX;YgwhenX=bcanbetypedusinganextraruleinthestyleofaccept,tobeinvokedfromthereceiveruleinFigure6.Ourtypesystemguaranteesthatallwithin-sessionmessageshaveachanceofbeingreceived.Itwouldbedesirabletoalsoguaranteethispropertyforsessioninitiationmessages,thuso eringstrongerbehaviourguarantees.Intuitively,weneedtoensurethatatanystate,termscanreceiveallpossiblesession-initiationmessages,eitherimmediatelyorbyreducingtoastatethatdoesso.Atechniquealongthelinesofnon-uniformreceptivitymayprovehelpful[1].Moreover,sinceErlanghasgeneralpatternmatching,itwouldbeusefultoallowguardstoimposeconstraintsonthevaluesreceived(e.g.,receiveonlyinteger5),andthiscanbeachievedbyusingdependenttypes.Delegationisthetermusedtodescribetheabilitytopassasessionidenti eronamessage.Itallows,e.g.,foraservertobalanceitsloadbysendingsome(open)sessionstootherservers.TheverynatureofErlangmakesdelegationadelicatematter,asopposedtothepicalculuswhereitisbuiltinthelanguage.DuetothenatureofErlangsemantics,wherecommunicationisbu ered,eachprocessisco-locatedwithitsmailbox,andmessagesareaddressedtopids,dele-gationrequiresafairlycomplexprotocol,andremainsoutsidethescopeofthiswork(ifinterestingatallinErlang).ApossiblesourceofinspirationmaycomefromtheworkonSessionJavawherearuntimeAPIimplementsadelegationprotocolforsocketbasedsessioncommunication[8].Inordertoconcentrateonthenoveltyofourproposal,wedeliberatelyex-cludedunboundbehaviour.Suchanextensionshouldbeeasytoincludevia,e.g.,recursivetermde nitions,asexplainedinSection3.Realisticexamplesmayre-quirerecursivetypes.Thisis,e.g.,thecaseofourexampleinSection2ifweallow