Event-based run-time adaptation in communication-centric systems

Communication-centric systems are software systems built as assemblies of distributed artifacts that interact following predefined communication protocols. Session-based concurrency is a type-based approach to ensure the conformance of communication-centric systems to such protocols. This paper presents a model of session-based concurrency with mechanisms for run-time adaptation. Our model allows us to specify communication-centric systems whose session behavior can be dynamically updated at run-time. We improve on previous work by proposing an event-based approach: adaptation requests, issued by the system itself or by its context, are assimilated to events which may trigger adaptation routines. These routines exploit type-directed checks to enable the reconfiguration of processes with active protocols. We equip our model with a type system that ensures communication safety and consistency properties: while safety guarantees absence of run-time communication errors, consistency ensures that update actions do not disrupt already established session protocols. We provide soundness results for binary and multiparty protocols.


Introduction
Context and Motivation.Modern software systems are increasingly built as assemblies of distributed artifacts that interact by following predefined communication protocols.Correctness in these communication-centric systems, therefore, depends on ensuring that such dialogues conform to their protocols.Sessionbased concurrency is a type-based approach to ensure conformance to prescribed protocols: dialogues are organized into units called sessions; interaction patterns are abstracted as session types [HVK98], against which specifications may be checked.As these specifications are often given in the π-calculus [MPW92,HVK98], protocol conformance can be analyzed at the level of concurrent processes.
As communication-centric systems typically operate on open and dynamic infrastructures, run-time adaptation appears as an indispensable feature to ensure their flexible and uninterrupted operation.Here we understand run-time adaptation as the dynamic reconfiguration of a system's behavior in response to an exceptional event.Examples of exceptional events are, e.g., a varying requirement or a local failure.These events are not necessarily catastrophic but are hard to predict.In this context, conformance to structured protocols and run-time adaptation appear as intertwined concerns: although the specification of run-time adaptation may not be strictly tied to protocol reconfiguration, steps of run-time adaptation have a direct influence in a system's communicating behavior and overall correctness.
We are interested in enhancing models of session-based concurrency with forms of run-time adaptation.This entails extending models of session-based concurrency with constructs for representing adaptation, but also developing appropriate analysis and verification techniques for such extended models.
As a first answer to this challenge, in previous work [DP13a,DP15] we extended a typed process framework for binary sessions with constructs from the model of adaptable processes [BDPZ12].In adaptable processes there are two key constructs, namely located processes and update processes: • Given a process P , the located process loc P denotes the fact that P resides in location loc.Locations are explicit delimiters for process behavior: they denote possibly nested computation sites.Since locations are transparent, process P in loc P may interact with processes outside loc.
• An update process loc{U } specifies that the behavior currently enclosed by location loc should be modified by the adaptation routine U -intuitively, a function from processes to processes located at loc.
At the operational level, located and update processes are complementary: processes loc P and loc{U } are meant to synchronize in order to realize an adaptation step.As we will see, U is applied to P by "moving" to its enclosing context.The exact operational semantics that justifies this adaptation step will be illustrated shortly.Observe that since processes within locations (such as P in loc P ) may implement one or several session protocols, the interaction with update processes allow us to specify adaptation routines that concern several running sessions.
We would like to guarantee that adaptation steps resulting from the synchronization of located and update processes preserve overall system correctness.In a session-typed setting this entails ensuring that such synchronizations do not jeopardize the session protocols enclosed by locations.As a simple example of a dangerous adaptation routine, consider the update process loc{0}, which says that the new behavior at loc should be the inactive process 0, without any considerations on the current behavior at loc.Indeed, a synchronization between loc P and loc{0} would result into process loc 0 , therefore discarding running session protocols in P .Processes depending on the sessions implemented by P would lack complementary partners, thus compromising any conceivable form of protocol conformance.
To rule out adaptation steps that jeopardize established protocols, communication and adaptation actions should be harmonized.In [DP13a,DP15] we defined the notion of consistency, according to which a located process can be updated only if it does not contain active (established) session protocols.Adaptation actions are enabled only for locations that do not enclose running sessions; an associated type system ensures protocol conformance but also that session protocols are never disrupted as a result of an adaptation step.This is a simple solution; since adaptation is enabled only when sessions in a location are in a quiescent state, it is an alternative that privileges communication over adaptation.In applications, however, it may be necessary to give communication and adaptation a similar status, enabling adaptation steps also on locations that contain already established sessions.The main contribution of this paper is a session-typed framework that enables this kind of adaptation steps, thus overcoming the limitations of the framework introduced in [DP13a,DP15].Next we elaborate on our approach.
Our Approach.To enable adaptation steps on locations that contain already established sessions, we propose update processes loc{U } in which the adaptation routine U (i) dynamically checks the current state of the protocols running in loc and (ii) determines a new process behavior for loc based on that state.
In their simplest form, our novel update processes concern located processes which implement only one session channel.They are of the form: where x is a channel variable, β 1 , . . ., β m are session types (cf.§ 2.1), and P 1 , . . ., P m are processes in which x occurs free.Intuitively, each pair (β i : P i ) represents an alternative for updating location loc: session type β i denotes the protocol state under which process P i will be used as the new implementation at loc.Suppose a process loc Q in which Q implements a session of type α along session channel κ.The interaction between loc Q and the update process in (1) intuitively proceeds as follows: If there is a β j (with j ∈ {1, . . ., m}) that "matches" with α, then the located process is updated to loc P j [ κ /x] .That is, the (current) protocol state α guides the selection of the j-th adaptation alternative.Otherwise, if no β j validates a match, then the located process is kept unchanged as loc Q and the update process is consumed.
In their general form, our novel update processes may act on located processes which enclose more than one running session, thus adding considerable expressiveness.Such an update process is denoted: where n is the number of running sessions at location loc.Intuitively, (β 1 j ; • • • ; β n j ) : P j denotes the j-th alternative for updating loc: session types β 1 j , . . ., β n j denote the protocol states under which process P j will be used as the new implementation at loc.That is, the update process in ( 2) is meant to interact with a located process loc Q in which Q implements session types α 1 , . . ., α n ; to enable an adaptation step, each α i must "match" with β i j for all i ∈ {1, . . ., n}.The semantics for our typeful update processes exploits session monitors-processes that maintain the (current) protocol state at a given channel-and constructs for dynamic type inspection, as put forward in [Kou12,KYHH16].
As just described, our update processes use types to select an alternative for adaptation-that is, types say how to adapt.However, update processes by themselves they do not specify when adaptation should be triggered.A simple solution is to "embed" update processes within session communication prefixes.Unfortunately, such a specification style would only allow to handle exceptional conditions which can be fully characterized in advance.Other important exceptional conditions, in particular contextual and/or unsolicited run-time conditions, cannot always be anticipated/predicated nor have a clear causal dependency with steps related to structured communications.
To offer a uniform solution to the issue of when to trigger update processes, we propose an event-based approach.Our process syntax includes adaptation signals that are similar to communication prefixes and that can be used to issue an adaptation request for a given location.Each location is endowed with a queue that stores its pending adaptation signals/requests.To detect a request r in the queue of loc and react accordingly, we use the arrival predicate arrive(loc, r), proposed in [Kou12].The use of adaptation requests and the arrival predicate allows us to maintain a separation between structured communications (disciplined by session types) and the events that ultimately trigger update processes.
As an example, let upd E denote an adaptation request.In our model we may specify process if arrive(loc, upd E ) then loc case x 1 , . . ., x m of {(β i 1 ; • • • ; β i m ) : P i } i∈I else Q which expresses an adaptation policy that checks for the arrival of a request upd E for location loc.If such a request is detected in the queue of loc then the update process in (2) is triggered; otherwise, process Q is executed.Let us write µX .P to denote a recursive process.The previous update process can be easily modified to express a persistent adaptation policy that uses recursion to continuously check for request upd E : We present a process model for session-based concurrency and run-time adaptation based on five constructs: located processes, typeful update processes, session monitors, adaptation signals, and location queues.While located processes are inherited from our previous work [DP15], the use of the other constructs for run-time adaptation is new to this presentation.We equip this model with a session type system that ensures the following key properties: • Safety: Well-typed programs do not exhibit communication errors (e.g., mismatched messages).
• Consistency: Well-typed programs do not allow adaptation actions that disrupt already established session protocols.
Safety is the usual guarantee expected from any session type discipline.In contrast, consistency is a guarantee peculiar to our model: it relates the behavior of the adaptation mechanisms with the preservation of prescribed typed interfaces.An example of inconsistent behavior is the interaction between loc P and loc{0} which, as motivated above, discards the running sessions in P .We prove that well-typed programs are safe and consistent: this ensures that specified session protocols are respected, while forbidding incautious adaptation steps that could disrupt the session behavior of interacting partners.
In the first part of the paper we consider a typed process model for binary sessions, as our goal is to develop our approach to event-based adaptation in a representative and well-established setting.Nevertheless, the key ingredients of our approach are sufficiently simple to be expressed in more general scenarios.Hence, in the second part of the paper, as a proof of concept, we describe a generalization of our approach to the case of multiparty, asynchronous communication.This generalization builds upon the framework developed in [CDV15], which we briefly describe next.
The framework in [CDV15] uses global types (or choreographies) and monitored processes as main ingredients.A global type abstracts a sequence of communications between two or more participants.By projecting a global type onto each participant, one obtains a series of local types.In [CDV15], such local types are used as monitors for the processes that implement each partner: a monitor enables the visible actions of the process.The association of a monitor and a process is called a monitored process.The whole choreography is implemented as a collection of monitored processes, or network.By considering a network together with a global state (data/values used to plan adaptation steps), one then obtains a system.
The approach in [CDV15] defines a separation between the global type, the monitors (local types), and the processes.Adaptation is specified at the level of global types, which include an explicit signal (called flag) that defines a form of anticipated adaptation between all participants of the choreography.As a result of this coordinated signal, an adaptation function determines a new choreography for the system, relying on the global state.Such a choreography determines new implementations for all partners, using a centralized repository of typed processes called collection.
We extend the framework of [CDV15] with typeful update processes and event-based constructs.As a result, we obtain an alternative framework in which adaptation is not specified at level of global types (unlike [CDV15]); instead, we have events that handle internal and external adaptation requests: − Internal adaptation requests are initiated by a participant that announces all other participants that the current global protocol should be abandoned, and that a new global protocol should be adopted instead.
− External adaptation requests are meant to dynamically update or upgrade the local implementation of a single participant.
To express internal adaptation requests, processes may explicitly output a message whose communication object denotes a choreography.This message can be accessed by all protocol participants (using the shared queue) so to determine their updated behavior.Networks in our model are distributed collections of locations, each containing a monitored process, a local collection of processes, and a queue.This queue is useful to model external adaptation requests which, as described above, are targeted to a particular participant.As a result, we obtain a setting in which internal adaptation is no longer anticipated at the level of types (therefore improving [CDV15]) and concerns all participants of the choreography, while external adaptation requests focus on a single participant.
Organization.The rest of the paper is organized as follows: − § 2 illustrates session-based concurrency, our approach and contributions by means of examples.− § 3 presents our process model of binary sessions with constructs for run-time adaptation.Then, § 4 presents our session type system, which ensures safety and consistency for processes with adaptation mechanisms (Theorem 4.11).
− In § 5 we generalize our approach to multiparty communications, defined as a variant of the framework given in [CDV15].We show communication safety and consistency of adaptation steps (Theorem 5.19).
− In § 6 we discuss related works and in § 7 we collect some concluding remarks.
The appendix collects omitted definitions and proofs.This work is an extended version of the paper [DP16].
Here we offer additional explanations and proofs of technical results.Moreover, the approach to adaptation for multiparty sessions ( § 5), not presented in [DP16], is a new contribution.

Our Approach, By Example
In this section we illustrate our approach and contributions by means of an example, the buyer-seller protocol.
To illustrate session types, consider two participants, a buyer and a seller, which interact as follows.First, buyer sends to seller the name of an item and seller replies back with its price.Then, depending on the amount, buyer may choose to add the item to her shopping cart or to close the transaction.In the latter case the protocol ends.In the former case, buyer must further choose a paying method.From buyer's perspective, this protocol may be described by the session type α buy = !item.?amnt.α pay where item and amnt are base types and α pay = ⊕{addItem : ⊕{ccard : α cc , payp : α pp } , cancel : end}.
Thus, session type α buy says that protocol α pay may only be enabled after sending a value of type item and receiving a value of type amnt.Also, addItem, ccard , payp, and cancel denote labels in the internal choice.Types α cc and α pp denote the behavior of each payment method.Following the protocol abstracted by α buy , code for buyer may be specified as a π-calculus process.Processes P and R below give two different specifications for buyer: P = x(book).x(a).if a < 50 then x addItem; x ccard ; P 1 else x cancel ; 0 R = x(game).x(b).ifb < 80 then x addItem; x payp; R 1 else x cancel ; 0 Thus, although both P and R implement α buy , their behavior is rather different, for they purchase different items using different payment methods (which are abstracted by processes P 1 and R 1 ).
Let us now analyze the situation for the seller.To ensure protocol compatibility and absence of communication errors, the session type for seller, denoted β sel , should be dual to α buy .Intuitively, duality decrees that every action from buyer must be matched by a complementary action from seller, e.g., every output in α buy is matched by an input in β sel .Formally, this duality is denoted α buy ⊥ C β sel (cf.Definition A.4). Thus, in our example, we let β sel = ?item.!amnt.β pay , where β pay = &{addItem : &{ccard : β cc , payp : β pp } , cancel : end} and β cc and β pp denote the duals of α cc and α pp , respectively.A process implementation Q for β sel is the following: where price stands for an auxiliary function.
The interaction of P and Q is defined using session initialization constructs: process u(x:α).P denotes the request of a session of type α; dually, u(x:α).P denotes the acceptance of a session of type α.In both cases, u denotes a (shared) name used for synchronization.In our example, we may have Thus, upon synchronization on u, a new session κ is established.Intuitively, in process S 0 session κ is "split" into two session channels (or endpoints) κ + and κ − : we write + and − to denote their opposing polarities [GH05], which make their complementarity manifest.The restriction (νκ) covers both channels, thus ensuring an interference-free medium for executing the session protocols described by α and β.
Session types may exploit a subtyping relation [GH05] to express useful relationships between protocol specifications.For instance, the type below defines a new payment method for seller: Intuitively, β gift extends β pay with an alternative on label giftc.It is safe to use an implementation for β gift wherever an implementation for β pay is required.The safe substitution principle that connects β gift and β pay is formalized by a subtyping, denoted ≤ C (cf. Definition A.4).This way, e.g., we have β pay ≤ C β gift .
Our Process Model and Approach.We are interested in expressing and reasoning about the run-time modification of session-typed processes such as P and Q above.Such modifications may be desirable as a reaction to exceptional run-time conditions (say, an error) or to implement unanticipated requirements.
Continuing our example, consider again process Sys (cf.(3) above).In our process model, detailed in § 3, we have the following reduction step: Session establishment creates session monitors κ + α buy and κ − β buy , processes that maintain the protocol state for the session at κ + and κ − , respectively.These monitors are essential to implement run-time adaptation policies that handle processes with running sessions.Reduction may proceed as follows: Observe how the session monitors evolve together with the process, capturing the evolution of the protocol state.In this example, they are useful to record the fact that the buyer part of S realizes the type ?amnt.α pay , whereas the seller part realizes the type !amnt.β pay .Suppose that we wish to modify at run-time the part of S realizing the buyer behavior.To preserve protocol correctness, a candidate new implementation must conform, up to ≤ C , to the type ?amnt.α pay ; a process realizing any other type will fail to safely interact with the part of S implementing the seller.
We now illustrate how located and update processes, distinctive of our model, could be used in the buyer-seller scenario.As a simple example, process W below W = sys buyer u(x:α buy ).P | seller u(y:β sel ).Q (5) represents an explicitly distributed variant of process Sys given in (3): the two partners now reside in different locations, namely buyer and seller; location sys encloses the whole system.Our process model allows us to define an update process that depends on the current protocol state of the two channels at location sys: sys case x, y of (α buy ; This update process defines two alternatives for adaptation: 1.If the current types for the two channels at sys are α buy and β sel (i.e., the protocol has just been established) then only the buyer is updated-its new behavior will be given by process R. 2. If the current types for the two channels at sys are α pay and β pay (i.e., both item and price information have been already exchanged) then new implementations P * and Q * are installed in the respective locations.
Session types are used to guide update processes, but also to ensure that the ensuing process alternatives are sound.The type system we develop in § 4 ensures that process buyer R | seller Q (the first alternative) has exactly two free session channels x and y, with session types α buy and β sel , respectively.A similar check applies to process buyer P * | seller Q * and α pay and β pay .As a simple example of the event-based constructs, we may consider a variant of the process given in § 1, which defines a conditional (and persistent) adaptation policy: Above, U bs denotes the update process in (6).Intuitively, the process in (7) persistently checks if an adaptation message upd E has arrived to the queue of location sys, which we denote sys r .(We shall write r, r 0 , r 1 , . . . to range over adaptation messages.)Notice that such a message may be issued by process W itself or by its context, using an adaptation signal, denoted loc(upd E ).We therefore envision systems in which communication actions, adaptation policies, and event-based constructs concurrently interact.In our example, we could have the process W | U | sys r 0 • r which triggers the adaptation of location sys if r 0 = upd E ; otherwise, the communication behavior of W would take place.

Multyparty Sessions
Background.In § 5 we consider multiparty sessions following the approach in [CDV15], which relies on global types, monitors, processes, networks, and systems.
In [CDV15], global types describe communications and explicit adaptation signals; monitors, derived from global types, describe the protocol from the perspective of a single participant.Processes only specify communicating behavior; they are associated to monitors that regulate their behavior and contain information on senders/receivers.Each protocol participant is then defined as a monitored process, a process tied with a monitor.Networks are collections of monitored processes, together with constructs for starting new global protocols and queues for handling asynchronous communication.A system is the composition of a network with a global state, a collection of data that may influence adaptation.
We introduce some notational conventions.Below, p, q, . . .denote participants and Π represents a set of participants.Also, l 1 , l 2 , . . .denote labels; S 1 , S 2 , . . .denote carried types (e.g., Bool, Int); and λ 1 , λ 2 , . . .denote adaptation flags.Global types abstract sequences of broadcast-like communications from a single participant to a set of participants; such communications include usual labeled messages and also explicit adaptation signals (flags).

G, G
The set of monitors is defined as follows: Each process owns a unique channel c.At run-time, channels specify a session channel and the identity of the participant.Most constructs are standard; processes op.P , c?l(λ, T).P , and c!l(λ(F ), T).P deserve additional explanations: − op.P denotes an operation on the global state; as such, it influences the behavior of future adaptation actions.− process c?l(λ, T).P receives an adaptation flag λ and has a continuation of type T. − process c!l(λ(F ), T).P specifies an adaptation function F which, in combination with the global state, will determine a new global type.
Given a monitor M and a process P , a monitored process is denoted M[ [P ] ].Adaptation actions manifest at the level of networks; they are realized directly over monitors but indirectly over processes: the modification of the global type of the system results into a new set of monitors associated to processes; if a current process does not "fit" its new monitor, then it must be replaced with a different process, obtained from a centralized collection of pairs (P, T), denoted P, a parameter of the framework.In [CDV15], this collection is assumed to be complete: it contains processes for all conceivable monitors.Formally, the fit between processes and monitors is defined as an adequacy relation, denoted ∝, which uses subtyping to relate the type of processes and monitors.
The semantics of processes is given in terms of a labeled transition system (LTS) in which actions describe a session and the current participant.These actions are used to enforce the consistency between a process and its associated monitor, as formally captured by the semantics of networks.This semantics describes how each participant reacts to an adaptation request (i.e., a new global type) issued by another participant.Depending on whether or not the current process is adequate to the new monitor then the process implementation is kept or replaced, as described before.
The semantics of systems specifies how a single participant communicates a new global type for the whole system.Indeed, as the selection of the new global type depends on the adaptation function F and the global state, the new global type can only be described at the level of systems, rather than at the level of networks.This selection is communicated to participants using the shared queue, and locally handled at the level of networks, as just explained.Notice the new global type may determine a new set of participants, and so some of the current participants may be excluded as a result of adaptation.The new global type may also determine a new implementation for the participant invoking global reconfiguration; here again adequacy is used to determine whether a process reconfiguration is required or not.
Our Process Model and Approach.Our example in § 2.1 can be extended to the multyparty scenario by adding a third participant (postal service) to the conversation.The extended protocol is as follows: the buyer b asks for an item to the seller s, who replies with its price.Then, b confirms its order and pays it by sending to s her credit card number and to the postal service p her address.Finally, s finalizes the order by sending the name of the item to p.As a global type, this protocol may be expressed as follows: In the multiparty scenario, our located process adopt a slightly different meaning than in the binary setting.Each location is associated to only one participant in the conversation and contains a local collection of typed processes P that represents possible programs to be run upon session establishment.That is, the collection assumed global in [CDV15] is now distributed to the local participants.The idea behind this choice is that a location may correspond to an autonomous "computing entity" possibly running distinct programs, as in, e.g., a smartphone where applications are installed and can be executed depending on the need.Thus the three participants above can be implemented in the distinct locations loc b , loc s , and loc p : Buyer: loc b P b ; loc b Seller: loc s P s ; loc s Postal Service: loc p P p ; loc p where, for each q ∈ {b, s, p}, loc q is an event queue used to signal the presence of an adaption routine; it has the same behavior as in the binary case.The collection P q contains an implementation of the local protocol of each participant (obtained projecting the global protocol into each participant).We therefore have the following processes in the respective local collections: P b ::= y!it(item).y?price(x).y!ok (true).y!card (number).y!ad (address) P s ::= y?it(x 1 ).(if (x 1 = item1) then y!price (1).y?ok (x 2 ).y?card (x 3 ).y!itname(x 1 ) else y!price(2).y?ok (x 2 ).y?card (x 3 ).y!itname(x 1 ) P p ::= y?ad (x 1 ).y?itname(x 2 ) In our proof of concept we define both external and internal adaptation.An internal adaptation routine is started by one of the participants who warns the others that a new protocol should be followed.External adaptation requests can be of two forms: they may either upgrade a process in the local collection or update the participant's current implementation using a type-directed check, following the update processes introduced for binary sessions.
As an example in the buyer-seller-postal service scenario, we can imagine that after having chosen an item, the buyer asks the other participants to change the protocol, as she wishes to change the payment method from credit card to bank transfer.This adaptation routine will cause the buyer and the postal service to change their implementations, while the postal service will remain unchanged.Moreover, a new participant (the bank k) will be added to the conversation.The new global protocol will then be: and the idea is that current communications are stopped, and the current active process is substituted with another one that implements the new protocol.The semantics for networks would lead to the following adapted process: (νκ)(loc b y!card (number).y!ad (address); P b ; loc b | loc s y?card (x).y!itname(x 1 ); P s ; loc s | loc p y?ad (x 1 ).y?itname(x 2 ); P p ; loc p ) −→ (νκ)(loc b y?iban(x).y!iban(x).y!ad (address); P b ; loc b | loc k y?iban(x); P k ; loc k loc s y!iban(ibstr).y!itname(x 1 ); P s ; loc s | loc p y?ad (x 1 ).y?itname(x 2 ); P p ; loc p ) We shall revisit this scenario in § 5-see Example 5.8.

Event-Based Adaptation for Binary Communications
Syntax.We rely on base sets for names, ranged over by u, a, b . ..; (session) channels, ranged over by k, κ p , . .., with polarity p ∈ {+, −}; labels, ranged over by n, n , . ..; and variables, ranged over by x, y, . ... Values, ranged over v, v , . .., may include booleans (written false and true), integers, names, and channels.We use r to range over adaptation messages, such as upd E in ( 7) above.We use • to denote finite sequences.Thus, e.g., x is a sequence of variables x 1 , . . ., x n .We use to denote the empty sequence.Table 1 reports the syntax of expressions and processes.Processes include usual constructs for input, output, and labeled choice.Common forms of recursion, parallel composition, conditionals, and restriction are also included.Constructs for session establishment are annotated with a session type α, which is useful in derived static analyses.A prefix for closing a session, inherited from [DP15], is convenient to better structure specifications.Variable x is bound in processes u(x:α).P , u(x:α).P , and k(x).P .Binding for name and channel restriction is as usual.Also, recursion variable X is bound in process µX .P .Given a process P , its sets of free/bound channels, names, variables, and recursion variables-noted fc(P ), fn(P ), fv(P ), fpv(P ), bc(P ), bn(P ), bv(P ), and bpv(P ), respectively-are as expected.We always rely on usual notions of α-conversion and (capture-avoiding) substitution, denoted [ k /x] (for channels) and [ P /X ] (for processes).We write [ k 1 , . . . ,kn /x 1 , . . ., xn] to stand for an n-ary simultaneous substitution.Processes without free variables or free channels are called programs.
Up to here, the language is essentially a synchronous π-calculus with sessions [HVK98].As motivated in the Introduction, building upon locations loc, l 1 , l 2 , . .., we consider the following novel process constructs for run-time adaptation: Moreover, expressions now include the arrival predicate arrive(loc, r).
We now comment on these elements.Located processes and update processes have been already discussed.Here we just remark that update processes are assumed to refer to at least one variable x i and to offer at least one alternative Q i .Also, variables x 1 , . . ., x n are bound in loc case x 1 , . . ., x n of {(β Update processes generalize the typecase introduced in [Kou12], which defines a case-like choice based on a single channel; in contrast, to specify adaptation for locations with multiple open sessions, our update processes define type-directed checks over one or more channels. Update processes go hand-in-hand with monitors, run-time entities which keep the current protocol state at a given channel.We write κ p α to denote the monitor that stores the protocol state α for channel κ p .In [Kou12], a similar construct is used to store in-transit messages in asynchronous communications.For simplicity, here we consider synchronous communication; monitors store only the current protocol state.This choice is aligned with our goal of identifying the elements from the eventful session framework that are essential to run-time adaptation (cf.Remark 4.12).
Location queues, not present in [Kou12], handle adaptation requests, modeled as a possibly empty sequence of messages r.Location queues enable us to give a unified treatment to adaptation requests.Given loc r , it is worth observing that messages r are not related to communication as abstracted by session types.This represents the fact that we handle adaptation requests and structured session exchanges as orthogonal issues.An adaptation signal loc(r) enqueues request r into the location queue of loc.To this end, as detailed below, the operational semantics defines synchronizations between adaptation signals and location queues.To connect run-time adaptation and communication, our language allows the coupling of update processes with the arrival predicate on locations, denoted arrive(loc, r).Inspired by the arrive predicate in [Kou12], this predicate detects if a message r has been placed in the queue of loc.
Our process language embodies several concerns related to run-time adaptation: using adaptation signals and location queues we may specify how an adaptation request is issued; arrival predicates enable us to specify when adaptation will be handled; using update processes and monitors we may specify what is the goal of an adaptation event.
Semantics.The semantics of our language is given by a reduction semantics, the smallest relation generated by the rules in Table 2.We write P −→ P for the reduction from P to P .Reduction relies on a standard notion of structural congruence, denoted ≡ (see Appendix A).It also relies on evaluation and location contexts: ) to denote the process (resp.expression) obtained by filling in occurrences of hole − in C with P (resp. in E with e).We comment on the reduction rules below.The first four rules formalize session behavior within hierarchies of nested locations.Using duality for session types, denoted ⊥ C (cf. Definition A.4), in Rule r:Open the synchronization on a name u leads to establish a session on fresh channels κ p and κ p ; also, two monitors with the declared session types are created.Duality for polarities p is as expected: + = − and − = +.By construction, monitors are local, i.e., they are created in the same contexts in which the session is established.Rule r:Com represents communication of a value: we require both complementary prefixes and that the monitors support input and output actions.After reduction, prefixes in processes and monitors are consumed.Similarly, Rule r:Sel for labeled choice is standard, augmented with monitors.Rule r:Clo Reduction semantics for binary processes.Above, α and β denote session types.
formalizes session termination, discarding involved monitors.The monitors in these three rules allow us to track the evolution of active session protocols.The following five rules in Table 2 define our event-based approach to run-time adaptation.Before commenting on them, we require two auxiliary definitions: Definition 3.1 (Matching).Given an index set I of alternatives, session types α 1 , . . ., α m , and an indexed sequence of session types {β 1 i , . . ., β m i } i∈I , we define Intuitively, match I ({α 1 , . . ., α m }, {β 1 i , . . ., β m i } i∈I ) = l says that the l-th alternative ensures a match (up to subtyping) between types α j and β j l , for all j ∈ [1, . . ., m].If there is no alternative satisfying the match (i.e., for every alternative n there is a pair α j and β j n for which match does not hold) then the function is undefined, which is denoted by ↑.Definition 3.2 (Barbs).Let P be a process.We write P ↓ κ p if P is structurally congruent to one of the following: We write barbs(P ; Q) whenever P ↓ κ p if and only if Q ↓ κ p .
We may now return to describing the reduction rules: − Rule r:UReq treats the issue of an adaptation request r as a synchronization between a location queue and an adaptation signal.The queue and the signal may be in different contexts; this enables "remote" requests.− Rules r:Arr1 and r:Arr2 resolve arrival predicates by querying the (possibly remote) queue r. − Rules r:Upd1 and r:Upd2 define the update of the behavior at location loc.Given an index set I over the update process, suitability with respect to the behavior at loc is defined by the function match I (cf.Definition 3.1).There are two possibilities.If there is no matching alternative then the current protocol state at loc is kept unchanged (Rule r:Upd1 ).Otherwise, the predicate holds for an alternative that defines a new protocol state which preserves the barbs of the current state (Rule r:Upd2 ).By an abuse of notation, we write P 1 ∈ P to indicate that P 1 occurs in P , i.e., if P = (ν κ)C P 1 for some C and κ.
In addition, our semantics includes standard and/or self-explanatory treatments for reduction under evaluation contexts, parallel composition, located context, and restriction.Also, it accounts for applications of structural congruence, recursion and conditionals.
Example 3.3.Recall process W given in § 2.1, Equation (5).According to our semantics: Suppose that following an external request the seller must offer a new payment method (a gift card).Precisely, we would like the seller to act according to the type β gift given in (4).Let α gift be the dual of β gift .We then may define the following update process: xy keeps the expected implementation for the buyer (P ), but updates its associated monitor.For the seller, both the implementation and monitor are updated; above, Q is a process that offers the three payment methods.We may then specify the whole system as: W | µX .ifarrive(sys, upd E ) then R 1 xy else X .The type system introduced next ensures, among other things, that updates such as R 1  xy consider both a process and its associated monitors, ruling out the possibility of discarding the monitors that enable reduction.

Session Types for Eventful Run-time Adaptation
This section introduces a session type system for the process language of § 3. Our main result (Theorem 4.11) is that well-typed programs enjoy both safety (absence of run-time communication errors) and consistency properties (update actions do not disrupt established sessions).Our development follows the lines of the typed framework in [DP15].
Syntax.The syntax of session types (ranged over by α, β, . ..) has been presented in § 2.1.We consider basic types (ranged over by τ, σ, . ..) and write T, S, . . . to range over τ, α.Although our process language copes with run-time adaptation, our type syntax retains the intuitive meaning of standard session types [HVK98], which we now briefly recall.
Type ?(τ ).α (resp.?(β).α) abstracts the behavior of a channel which receives a value of type τ (resp.a channel of type β) and then continues as α.Dually, type !(τ ).α (resp.!(β).α) represents the behavior of a channel which sends a value of type τ and then continues as α.Type &{n 1 : α 1 , . . ., n m : α m } describes a branching behavior: it offers m behaviors, and if the j-th alternative is selected then it behaves as described by type α j (1 ≤ j ≤ m).In turn, type ⊕{n 1 : α 1 , . . ., n m : α m } describes the behavior of a channel which may select a single behavior among α 1 , . . ., α m and then continues as α j .We use end to type a channel with no communication behavior.Type µt.α describes recursive behavior; as usual, we consider recursive types under equi-recursive and contractive assumptions.
Along the paper we have informally appealed to duality and subtyping over session types (denoted ⊥ C and ≤ C , resp.).Since our session type structure is completely standard, we may rely on the (coinductive) definitions given by Gay and Hole [GH05]; see also Definition A.4.
Our typing judgments generalize usual notions with an interface I for each process.Based on the syntactic occurrences of session establishment prefixes a(x:α), and a(x:α), the interface of a process describes the services appearing in it.We annotate services with a qualification q, which may be 'lin' (linear) or 'un' (unrestricted).Intuitively, a service is linear if it is offered a finite number of times, otherwise it is persistent or unrestricted.Thus, the interface of a process gives an "upper bound" on the services that it may execute.The typing system uses interfaces to control the behavior contained by locations after an update.We have: Definition 4.1 (Interfaces).We define an interface as the multiset whose underlying set of elements is I = {q u:α | q ∈ {lin, un}} (i.e., a set of assignments from names to qualified session types).We use I, I , . . . to range over interfaces.We write dom(I) to denote the set {u | q u : α ∈ I} and # I (q u : α) = h to mean that u occurs h times in I.
The union of two interfaces is essentially the union of their underlying multisets.We sometimes write I a : α lin and I a : α un to stand for I {lin a:α} and I {un a:α}, respectively.Moreover, we write I lin (resp.I un ) to denote the subset of I involving only assignments qualified with lin (resp.un).We now define an ordering relation over interfaces, relying on subtyping: Typing Environments.We now define our typing environments, following [DP15].Recall that we write q to range over qualifiers lin and un.first-order environment (with α q ⊥ C β q ) Θ ::= ∅ | Θ, X : ∆; I | Θ, loc : I higher-order environment We consider typings ∆ and environments Γ and Θ. Typing ∆ collects assignments from channels to session types; it describes currently active sessions.In our system, ∆ also includes bracketed assignments, denoted κ p : α , which represent the type for monitors.Subtyping extends to these assignments ( α ≤ C β if α ≤ C β) and thus to typings.We write dom(∆) to denote the set {k p | k p : α ∈ ∆ ∨ k p : α ∈ ∆}.We write ∆, k : α where k ∈ dom(∆).Furthermore, we write ∆, k : α to abbreviate ∆, k : α, k : α .That is, k : α describes both a session and its associated monitor.
Γ is a first-order environment which maps expressions to basic types and names to pairs of qualified session types.The higher-order environment Θ collects assignments of typings to process variables and interfaces to locations.While the former concerns recursive processes, the latter concerns located processes.As we explain next, by relying on the combination of these two pieces of information the type system ensures that run-time adaptation actions preserve the behavioral interfaces of a process.We write vdom(Θ) = {X | X : I ∈ Θ} to denote the variables in the domain of Θ.Given these environments, a type judgment is of form Γ ; Θ P ∆; I meaning that, under environments Γ and Θ, process P has active sessions declared in ∆ and interface I.
Typing rules are shown in Tables 3 and 4. Below we comment on some of the rules in Well-typed processes: Typing rules (Part I).
ensures that each process Q i has exactly the same active sessions that those declared in the respective case.Also, we require that alternatives contain both processes and monitors.With I j I we guarantee that the process behavior does not "exceed" the expected behavior within the location.Rule t:sub takes care of subtyping both for typings ∆ and interfaces.Rule t:CRes types channel restriction; it ensures typing duality among partners of a session and their respective queues.Rule t:NRes types hiding of service names, by simply removing their declarations from the interface I of the process.In the rule, I u contains only declarations for u, i.e., ∀v = u, v / ∈ dom(I u ).Typing of queues is given by Rule t:Que that simply assigns type k : α to queue k α .
We now define and state safety and consistency properties.While safety guarantees adherence to prescribed session types and absence of run-time error s, consistency ensures that sessions are not jeopardized by careless run-time adaptation actions.Defining both properties requires the following notions of κ-processes and (located) κ-redexes: Definition 4.7 (κ-processes, κ-redexes, errors).A process P is a κ-process if it is a prefixed process with subject κ p , i.e., P is one of the following: κ p (x).P κ p (v).P close (κ p ).P κ p {n i :P i } i∈I κ p n.P Process P is a κ-redex if it contains the composition of exactly two κ-processes with opposing polarities, i.e., for some contexts C, D, and E, and processes P 1 , P 2 , . . ., P m , and P , process P is structurally congruent to one of the following: A located κ-redex is a κ-redex in which one or both of its constituent κ-processes are contained by least one located process.P is an error if P ≡ (ν κ)(Q | R) where, for some κ, Q contains either exactly two κ-processes that do not form a κ-redex or three or more κ-processes.
Informally, a process P is called consistent if whenever it has a located κ-redex then update actions do not destroy such a redex.Below, we formalize this intuition.Let us write P −→ upd P for any reduction inferred using Rule r:Upd2 (cf.Table 2).We then define: Definition 4.9 (Safety and Consistency).Let P be a process.
− We say P is safe if it never reduces into an error.− We say P is update-consistent if and only if, for all P and κ such that P −→ * P and P contains a κ-redex, if P −→ upd P then P contains a κ-redex.
Lemma 4.10.If Γ ; Θ P ∆; I with ∆ balanced then P is not an error process.
We now state our main result; it follows as a consequence of Theorem 4.6.
Theorem 4.11 (Typing Ensures Safety and Consistency).If Γ ; Θ P ∆; I with ∆ balanced then program P is safe and update-consistent.
Proof.Safety means that P never reduces into an error.Since ∆ is balanced, by Lemma 4.10 we know that P is not an error.Theorem 4.6 ensures that reduction preserves balanced typings; therefore, P never reduces to an error.Proving update-consistency entails showing that for all P 0 and κ such that P −→ * P 0 and P 0 contains a κ-redex, if P 0 −→ upd P 1 then P 1 contains a κ-redex.That is, P 0 has both the κ-redex and an update action which preserves it.By Theorem 4.6 we know that P 0 is well-typed under a balanced typing.To show consistency we distinguish two cases.The first case is when the κ-redex is not located in P 0 : then, the update action cannot affect it (i.e., the update concerns located process in P 0 which do not enclose the κ-processes that constitute the κ-redex) and the thesis follows.The second case is when the κ-redex is located in P 0 : therefore, κ-processes that constitute the κ-redex could be affected by the reduction P 0 −→ upd P 1 .There are several sub-cases, depending on which κ-processes are located.We consider the sub-case in which one κ-process (say, R 1 = κ p (x).R ) is located whereas the other (say, R 2 = κ p (v).R ) is not; other cases are similar.The proof follows directly from Rule r:Upd2 (cf.Table 2) which replaces R 1 with an alternative Q l .The rule not only ensures that R 1 and Q l have matching session types (up to subtyping) but also that they have the same barbs, i.e., the same top-level actions.This ensures that the κ-redex is preserved under the reduction −→ upd , and so the thesis follows.
Remark 4.12 (Asynchronous Communication).In this section, we have focused on synchronous communication: this allows us to give a compact semantics, relying on a standard type structure.To account for asynchrony, we would require a run-time syntax for programs with queues for in-transit messages (values, sessions, labels).The type system should be extended to accommodate these new run-time processes.In our case, an extension with asynchrony would rely on the machinery defined in [Kou12]; we present such a machinery (for multiparty sessions) in the following section.Remark 4.13 (Incremental Adaptation).Adaptation in our framework is "incremental" in that modifications always preserve/extend active session protocols, exploiting subtyping.Our framework can be modified so that arbitrary protocols are installed as a result of an update.One would need to ensure that the two endpoints of a session are present in the same location: arbitrary updates are safe as long as both endpoints are simultaneously updated with dual protocols.This alternative requires modifying definitions for matching (Definition 3.1) and interface ordering (Definition 4.2).

Event-Based Adaptation for Multiparty Communications
Here we generalize our approach to the case of multiparty communications.As already explained, we present a proof of concept that integrates type-directed constructs for update and eventful constructs for adaptation requests into the framework put forward by Coppo et al. [CDV15].
As described in § 2.2, in the framework of [CDV15] communication actions from adaptation mechanisms are tied together, as adaptation flags occur within global type specifications at the same level of protocol exchanges.Our event-based approach treats adaptation at the level of processes, defining a separation between communication and adaptation concerns, which in our opinion is beneficial for specification and analysis.
Integrating our event-based approach entails novelties with respect to the notions of global types and networks in [CDV15].Monitored processes will be now embedded into distributed locations which contain local collections and queues that govern local and external adaptation.Furthermore, at the level of processes we replace processes c?l(λ, T).P , and c!l(λ(F ), T).P with a construct c!(G).P which enforces a locally-motivated adaptation based on global type G. Overall, we have a two-level framework of processes and systems (instead of processes, networks, and systems, as in [CDV15]).

Global Types
Global types specify structured interactions between two or more participants.We distinguish between communication and adaptation concerns; for this reason, unlike [CDV15], our global types do not mention synchronizations related to adaptation.We write p, q, . . .and Π, Π , . . . to denote participants and sets of participants, respectively.Exchange of values take place on labels, denoted λ, λ , . . . in the sequel, which are useful to express choices.We write loc, loc , . . . to range over locations.As in [CDV15], we assume that communicated values are extracted from a set of sorts S. Formally, we have: Definition 5.1 (Global Types).The set of global types is defined by As we follow [CDV15], our syntax of global types is admittedly simple: a global type p → q : {λ i (S i ).G i } i∈I represents a labeled communication from participant p to participant q.Global type end denotes the terminated protocol.We write part(G) to denote the set of participants declared in G.

Monitors
Monitors capture the local view that participants have of a global type.They are used to enable actions of the process implementations; they also contain information on the participants and labels involved in the directed exchanges.

Definition 5.2 (Monitors).
The set of monitors is defined by: An input monitor p?{λ i (S i ).M i } i∈I can be associated to a process which can receive, for each i ∈ I, a value of sort S i with label λ i , with a continuation that is associated to M i (external choice).The output monitor p!{λ i (S i ).M i } i∈I is dual: it can be associated to a process which sends a value of sort S i , distinguished by label λ i , for each i ∈ I, with a continuation that is associated to M i (internal choice).
Following the approach of multiparty session types [HYC08], the monitor of a participant is obtained via a projection function, defined below.Definition 5.3 (Projection of a Global Type).The projection of a global type G onto a monitor for a participant p, denoted G ↓ p , is defined as follows: We will say that a global type is well-formed if its projections are defined for all participants.We shall work only with well-formed global types.We assume that each well-formed G is associated with a mapping L G from participants to locations such that p = p implies L G (p) = L G (p ), for all p, p ∈ part(G).

Process Types
We now describe types for the process language that will be introduced in Definition 5.6.While in multiparty session types [HYC08], the process types correspond to local types (the projection of the global type  5. Typing rules for multiparty processes. onto every participant), the approach in [CDV15] uses a discipline of process types which is different from local types (i.e., monitors).This adds flexibility, and is useful to establish an independence between local implementations (as formalized by processes) and choreographic coordination (as formalized by global types and monitors).Clearly, process types cannot be completely independent from monitors; a basic coherence between the two should exist.This coherence is defined in terms of adequacy (cf.Definition 5.5), a relation that uses subtyping to determine which process types "fit" a given monitor.Following [Pad10], the process types defined on [CDV15] exploit intersection and union types; this ensures an intuitive subtyping relation.Here we consider a syntax for process types that is certainly closer to the local types of [HYC08] than the syntax in [CDV15].This is for the sake of presentation, as we wish to keep a simple conceptual relation with the binary session types introduced in § 4. We then have: Definition 5.4 (Process Types).The syntax of process types is defined as follows: We write T to denote the set of all types, and use T, T , . . . to range over process types.Thus, intuitively, process types &{λ i (S i ).T i } i∈I and ⊕{λ i (S i ).T i } i∈I are used to type labelled inputs and outputs, respectively.Recursive types are as expected, following usual considerations for type equality.
An environment Γ is a finite mapping from expression variables to sorts and from process variables to types: Γ ::= ∅ | Γ, x : S | Γ, X : T where notation Γ, x : S (resp.Γ, X : T) means that x (resp.X) does not occur in the domain of Γ.
We now introduce typing judgments for expressions e and processes P : Γ e : S Γ P c : T Expressions are typed by sorts; we assume standard typing rules.The judgments for processes which makes it explicit that processes with at most one channel can be typed.
Typing rules for processes are given in Table 5. Due to the absence of explicit flags for adaptation, they are a subset of the typing rules given in [CDV15].We also consider Rule M:Adapt which represents the fact that internal adaptation requests are defined independently from communication protocols abstracted by types.
The relation between process types and monitors is formalized via adequacy.Adequacy relies on a subtyping relation, here denoted ≤; it corresponds to a finite variant of the subtyping ≤ C (formally given in Definition A.4).Our notion of adequacy is simple, and highlights how the difference between monitors and process types lies in the information about participant identities: Definition 5.5 (Adequacy).Let | • | be a mapping from monitors to types defined as follows: We then say that type T is adequate to monitor M (notation T ∝ M) if T ≤ |M|.

Syntax
Processes abstract the protocol implementations for each participant.The association of a process P with a monitor M results into a monitored process M[ [P ] ], which realizes the behavior of a single participant.As hinted at above, the main differences of our framework with respect to [CDV15] appear at the level of monitored processes and networks (collections of monitored processes).
The definition of processes implementing multiparty services, given next, is rather standard.We have operators for sending and receiving messages, conditionals, and recursion.On top of these operators we add a primitive for broadcasting an internal adaptation request, denoted c!(G).P .Intuitively, this primitive is an output action that mentions a new global type to be implemented by protocol participants.Definition 5.6 (Processes).The syntax of processes is defined as: Each process owns a unique channel, denoted y.Given a session κ and a participant p, channel y in the user code is substituted at run-time by a session channel κ[p].In the following we write c to denote either y (the user channel) or κ[p] (the session channel).We assume that processes pass around expressions, defined as expected.Every expression e reduces to a value v; this is denoted e v.As an example of internal adaptation requests, suppose participants p 1 , . . ., p j , . . ., p n establish session κ to communicate according to a specific protocol (say, Skype).To request a protocol change, participant p j may issue an adaptation request to all its partners by including the process κ[p j ]!(GTalk).P in its local implementation.As we will formalize later on, this request will arrive to the event queue of session κ, and then all participants will proceed to adapt their local behavior to the new global type GTalk.
Our notion of networks departs significantly from that in [CDV15] by considering an explicitly distributed setting based on (inactive) locations and event queues:

external adaptation: update request
A location represents a place where several programs can be executed.We assume a preexisting set of locations which are "filled in" with appropriate monitored processes upon initialization of global types (see below).An active location loc M[ [P ] ]; P; loc r is composed of a monitored process M[ [P ] ], a local collection of typed processes P (i.e., a set of pairs (Q, T ) where Q is a process and T is its corresponding type), and a queue loc r (where r stands for an external adaptation request).For simplicity, we assume that in each location only one session can be active.An inactive location is simply a location without a monitored process.The queue of a location connects it to an unspecified environment that can (i) add new processes to the collection (or upgrade the an existing process), or (ii) update the behavior of a monitored process.This is similar to the update processes for the binary framework.
As we shall see, initializing a global type G entails setting up monitored processes in appropriate locations, establishing a session channel κ, and creating a message queue κ : h for supporting asynchronous communication.We write ∅ to denote the empty message queue; messages are of the form (p, q, λ(v)) thus denoting the fact that participant p sends value v and label λ to participant q.Message concatenation is denoted with '•'.Table 6.LTS for multiparty processes.
The event queue κ e h handles internal adaptation requests, associated to process c!(G).P introduced earlier.

Semantics
The semantics of networks is given in terms of a reduction relation, denoted N −→ N .We require some auxiliary definitions, in order to connect the behavior of monitors and processes to that of whole networks; we also require a structural congruence to capture, among other things, asynchronous message communication as handled via queues.As in [CDV15], we assume that all local collections P are complete, which intuitively means that such collections contain all conceivable pairs of processes and types.
LTS for Monitors and Processes.Reduction for networks relies on LTSs for monitors and processes.The LTS for monitors is rather simple; it is used to enable the actions to be performed by processes: The LTS for processes relies on the following set of labels, with associated rules as in Table 6.
Structural Congruence.Reduction for networks relies also on a structural equivalence and on evaluation contexts.The structural equivalence on networks, denoted ≡, defines parallel composition as a commutative, associative operator, and which allows restriction to reduce and enlarge their scope without name clashes.Also, it decrees that any monitored process with the end monitor corresponds to the neutral element for parallel composition and absorbs restriction.More formally: We consider also a structural equivalence for message queues which allows us to commute messages involving different receivers or senders: This congruence is extended to networks in the expected way by letting: h ≡ h implies κ : h ≡ κ : h .Finally, we have the following definition for evaluation contexts, denoted E: Reduction Rules for Networks.The rules of the reduction semantics for networks are given in Table 7; we now describe them: − Rule N:Open initializes a global type, denoted G in the rule.To that end, it considers all the inactive locations associated to the declared participants of G, denoted Π.For each p ∈ Π, a process implementation is picked up from the local collection P p .The process type of this implementation is expected to be adequate to the monitor G ↓ p .Observe that mapping L G ensures that each participant is assigned to a different (inactive) location.A fresh session name κ is created for protocol participants; associated message and event queues are also created.
locq Pq; locq Table 7. Reduction semantics for multiparty processes.− Rules N:Send and N:Recv regulate output and input actions from/to the message queue of an established session.The action must be enabled by the label of the monitor, which also describes information on the receiver/sender of the exchanged value.Both monitors and processes evolve as a result of the interaction with the queue.In both rules, a reduction is enabled provided the event queue is empty.
− Rule N:Tau formalizes the fact that evaluation of conditional expressions and recursion unfolding within a (monitored) process can occur without affecting its monitor.
− Rules N:InMsg and N:InUpd formalize internal adaptation.Similarly as Rule N:Tau , issuing an internal adaptation request is a behavior specified by the process but independent from its monitor.
where k ∈ I, p = q and ∀i, j where k ∈ I, p = q and ∀i, j ∈ I M i = M j Table 8.Projection of generalized types onto participants.
Remark 5.9 (Adaptation Functions).We have proposed using processes communicating global types (here denoted c!λ(G).P ), rather than adaptation flags, to specify internal adaptation, i.e., adaptation requests issued by the system itself.This is a simple way of formalizing this important class of adaptation routines.As an alternative, a less direct mechanism would consist in communicating a value on which a future adaptation should depend on, rather than the expected new choreography.Such a value could be used as a parameter for the adaptation functions used in [CDV15].This would add flexibility to the specification of internal adaptation requests.
Having introduced networks and their semantics, we now proceed to investigate type-based analysis techniques for them.

Safety and Consistency
This section generalizes the results of § 4 to the multiparty asynchronous case.In order to lighten the syntax, the types for networks do not include any information on interfaces and only describe an active session.Indeed, as interfaces provide information about the services the location may execute and as each location contains a complete collection of processes P then the interface type will be the same for each location.We have already described how to type a process, we now show how to type its monitor and relative queues and how to combine them into networks.
As communication is asynchronous the information on the type of a session participant p (κ[p]) can be split between the process implementing the session and the associated session queue.We thus have generalized types, which can be either a message type, a monitor type or the combination of the two.More precisely: Definition 5.10.Session types, generalized types, message and queues types are defined by: Session types The typing judgments for networks are of shape where Σ lists the free session names in N .As for the binary case, type safety relies on a notion of balanced typing: communications are performed in the right order and with the proper type.The definition of duality is the same as for the binary case (see Definition A.2).
It is easy to see that session types obtained from the projection of global types are balanced.
Proposition 5.12.Let G be a global type and p = q, then (G ↓ p ) ↓ q (G ↓ q ) ↓ p .
We are now ready to complete the typing system with typing rules for networks and queues, given in Table 9.We briefly comment on the rules.A session initiator is typed with the empty session typing ] is typed with the empty session type (Rule M:End ); otherwise, if the type of P is adequate with respect to the monitor then the type of the monitored process is κ[p] : M (Rule M:MP ).The event queue κ e is typed with the completed session type (Rule M:CQueue ).Rules M:Qinit and QSend type the session message queue.In particular, Rule M:Qsend makes use of the operator # that dispatches message types to proper session channels: Rule M:Par combines networks; it relies on an operator , which combines the typing information coming from queues and monitored processes: In order to take into account the structural congruence on queues (Rule M:Equiv ) we build an equivalence relation (≈) on types that is induced by the following equivalence rule on message types: m; q!λ(S); q !λ(S ); m ≈ m; q !λ(S ); q!λ(S); m with q = q , and is extended to generalized types by letting if m ≈ m then m, M ≈ m , M .
As expected, the type of a restricted network depends on the consistency of the session κ (Rule M:Res ).Finally, Rules M:Loc1 and M:Loc2 are used to type locations: as in the binary case, locations do not add any information to the session type.We now state the subject reduction theorem, which guarantees that communications are performed by (located) monitored process in a safe manner, following the protocols prescribed by global types.Similarly as for the case of binary sessions, we introduce a reduction over session types.Definition 5.14 (Reduction for Typings).Reduction for typings, denoted ∆ −→ ∆ , is defined by the following rules: 1. ∆, κ[p] : h , q!λ(S).M −→ ∆, κ[p] : q!λ(S); h , M 2. ∆, κ[p] : q!λ(S); h , M , κ[q] : h , p?λ(S).M −→ ∆, κ[p] : h , M , κ[q] : h , M Theorem 5.15 (Subject Reduction).If Γ Σ N ∆ with ∆ balanced and N −→ N then Γ Σ N ∆ , for some balanced ∆ such that either ∆ = ∆ or ∆ −→ ∆ .
Proof.By induction on the last rule applied in the reduction.See Appendix B for details.
Notice that we can also prove a form of progress: i.e., in the absence of internal adaptation events (only external adaptation), every input monitored process will eventually receive a message and conversely every message in a queue will eventually be received by an input monitored process. 1 The proof follows the one presented in [CDV15,CDYP16], which crucially depends on the assumption that a process owns only one session channel.
We now extend safety and consistency properties to the multiparty case.Similarly as before we define κ-redexes, and error processes.Major changes are due to the fact that here we consider asynchronous communication.
Definition 5.16 (κ-redexes, errors).A network N contains a κ-redex if it is of one of the following forms: where M in = p?{λ i (S i ).M i } i∈I , M o = p!λ(S).M and there exists j ∈ I such that λ j = λ and S j = S.
A network N ≡ (ν κ)(N ) is an error if N does not contain a κ-redex.
The introduction of internal updates breaks the update-consistency property as stated in § 4.This is expected, as internal updates are meant to globally change the communication protocol agreed upon session establishment.Nonetheless, as external updates behave exactly as in the binary case, the property is preserved for them.Below we write N −→ upd N for any reduction inferred using Rule N:Updloc1 (cf.Table 7).We may then define: Definition 5.17 (Safety and Consistency).Let N be a network.
− We say N is safe if it never reduces into an error.− We say N is external update-consistent if and only if, for all N 0 and κ such that N −→ * N 0 and N 0 contains a κ-redex, if N 0 −→ upd N 1 then N 1 contains the same κ-redex.
As before our main result follows as a consequence of Theorem 5.15.
Lemma 5.18.If Γ Σ N ∆ with ∆ balanced then network N contains no error.
Proof.Follows directly from Definition 5.11.
Theorem 5.19 (Typing Ensures Safety and Consistency).If Γ Σ N ∆ with ∆ balanced then network N is safe and external update consistent.
Proof.Safety means that N never reduces into an error.Since ∆ is balanced by Lemma 5.18 we know that N is not an error.Theorem 5.15 ensures that reduction preserves balanced typings; therefore, N never reduces to an error.Proving update-consistency entails showing that for all κ such that N 0 contains a κ-redex, and N −→ * N 0 , if N 0 −→ upd N 1 then N 1 contains the same κ-redex.By Definition 5.16 N 0 , there are two cases.We consider only the case (a), i.e., the redex is of the form as case (b) is similar.If Rule N:Updloc1 is applied either loc p or loc q are updated.Without loss of generality suppose that loc p is updated.Now function match guarantees that the type of the updated process P located in loc p is kept unchanged.As P only implements the behavior of participant p, by inversion on typing we know that the κ-process needs to be present also in the updated process.Thus we can conclude that the κ-redex is still present.

Related Work
Many previous works have investigated formal approaches to dynamic/run-time adaptation in different settings; below we describe some of these efforts.An early work devoted to software process evolution is [JC93], which describes the EPOS approach to evolution and customization.Correctness criteria for adaptive workflows are surveyed in [RRD04].In the setting of workflows, modifications may occur at the level of schemas or at the level of individual workflow instances.It is natural to represent workflows as (Petri) nets with special characteristics; as such, the focus of the comparison in [RRD04] is on approaches based on Petri nets with different semantics.Two correctness criteria compared are graph equivalence (focused on changes in schemas) and trace equivalence (focused on changes in instances).The work [MGR04] describes a workflow management system that supports rule-based adaptation; it provides automated support for predictive and reactive adaptation strategies.The modeling approach and checked properties in these works are considerably different from those in our work.
The paper [Fox11] develops a model for dynamically adaptive services using COWS (the Calculus for Orchestration of Web Services).In particular, a model for adaptation managers is proposed; it exploits the constructs that COWS provides for timed behaviors, and the associated model checker CMC.The proposed model enables structural and functional modifications: while the former concerns the system configuration graph, the latter involves component replacement.Services are assessed in terms of responsiveness, availability, and reliability.This work does not appeal to static verification based on behavioral types.Also, properties related to protocol conformance, such as safety or consistency, are not explicitly considered in [Fox11].
To the best of our knowledge our work develops the first application of constructs for type-directed checks and event-based communication for specifying and analyzing run-time adaptation for session-based concurrent systems.In fact, although such constructs have been proposed in previous works, their application for run-time adaptation seems to be a new contribution of our work.As such, our work develops an unexplored perspective for existing elements in session-based languages with the aim of enhancing models and reasoning techniques for communication-centric systems which may be updated at run-time.
The combination of static typing and type-directed tests for dynamic reconfiguration is not new.For instance, the work [SC06] studies this combination in the very different setting of object-oriented component programming.As already discussed, we build upon constructs proposed in [HKP + 10, KYH11, KYHH16, Kou12] for defining type-directed checks and expressing eventful sessions.The earliest works on eventful sessions, covering theory and implementation issues, are [HKP + 10, KYH11].Kouzapas's PhD thesis [Kou12] provides a unified presentation of the eventful session framework, with case studies including event selectors (a building block in event-driven systems) and transformations between multithreaded and event-driven programs.At the level of types, the work in [Kou12] introduces session set types to support the typecase construct.In contrast, we use dynamic type inspection only for run-time adaptation; in [Kou12] typecase is part of the process syntax.This choice enables us to retain a standard session type syntax.
Previous works [DP15, AR12, BCH + 13, CDV15, CDP14, DGL + 14] have addressed forms of run-time adaptation for models of communicating systems based on binary and multiparty session types.As we elaborate next, none of them features the distinctive constructs of our framework: adaptation routines based on type-directed checks on session protocols and eventful constructs that handle and trigger such routines.
We have already mentioned how the present development was motivated as an enhancement to our previous work [DP15], in which update processes do not consider type-directed checks and adaptation of located processes with running sessions is disallowed by typing.While [DP15] addresses binary session types, all of [AR12, BCH + 13, CDV15, CDP14, DGL + 14] concern models based on multiparty sessions and/or choreographies.The work [AR12] studies dynamic update for message passing programs; a form of consistency for updates over threads is ensured using multiparty session types, following an asynchronous communication discipline.The paper [BCH + 13] develops a model of choreographies with interleaved sessions and adaptation as well as an associated endpoint language; however, typing is not addressed.The key ideas of the self-adaptable multiparty sessions in [CDV15] have been summarized in § 2. Our proposal for event-based adaptation for multiparty protocols, described in § 5, departs from the approach in [CDV15] and extends it to cover forms of unanticipated adaptation, including internal and external adaptation requests.Another work derived from [CDV15] is [CDP14] in which adaptation of multiparty protocols is coupled with mechanisms for enforcing secure information flow and access control.As such, it is both technically and conceptually different from the framework that we have developed in § 5. Finally, the paper [DGL + 14] describes a framework for programming distributed adaptive applications.The framework relies on a language for choreographies in which adaptation is specified following a rule-based approach.
The work [BCD + 13] develops a monitored variant of the π-calculus and equips it with a combination of static and dynamic verification techniques based on multiparty session types.The goal is to ensure that a collection of decentralized and possibly monitored local processes properly implement a protocol given as a global type.As in our work, in [BCD + 13] we find located processes which represent principals; a network is a set of principals with a global queue-a global transport.The semantics of global specifications induces assertion environments which in turn are essential to define the behavior of monitored networks: a network may performed actions allowed by its monitor.Key properties include transparency and safety: while transparency says that a monitored process/network behaves as an unmonitored (but well-behaved) process/network, safety says that a protocol (local and global) is respected.

Concluding Remarks
In this paper, we have introduced a novel approach to run-time adaptation of communicating processes whose structured protocols adhere to a session type discipline.Our study has addressed the case of protocols abstracted as binary sessions; as a proof of concept, we have also explored the case of adaptation in multiparty sessions with asynchronous communication.
Our approach is based on two kinds of constructs: (i) an update process construct based on type-directed checks and (ii) on constructs for eventful sessions, namely queues equipped with an arrival predicate.This combination of constructs allows us to specify dynamic modifications on the behavior of session-typed processes, therefore providing a basis for reasoning about expressive models of communication-centric systems with run-time adaptation.We may specify what should be the content of an adaptation routine, but also when it should be triggered.The constructs on which our approach relies are not new to this paper, but have been introduced and throughly studied by Kouzapas et al. in a series of works [HKP + 10, KYH11, KYHH16, Kou12].Such works investigate foundational and practical issues for eventful binary sessions; in our view, this adds significant value to our proposal, as the key syntactic elements on which it stands have been already validated (in theory and in practice) by previous independent studies.
The case of binary sessions represents a well-studied and representative setting, in which the distinguishing aspects of our approach can be cleanly introduced.We identified the strictly necessary eventful process constructs that enhance and refine the mechanisms for run-time adaptation given in [DP13a,DP15].Adaptation requests are handled via event detectors and queues associated to locations.Our approach enables us to specify rich forms of updates on locations with running sessions; this is a concrete improvement with respect to [DP15], in which updates are only allowed when locations do not enclose running sessions.To rule out update steps that jeopardize running session protocols, we also introduced a type system that ensures communication safety and update consistency for session programs.
Concerning our proof of concept for multiparty sessions, we described how our approach can be integrated on top of the framework for self-adaptable multiparty, asynchronous sessions by Coppo et al. [CDV15].In this more general setting we may specify internal and external adaptation requests; we rely on a process model which organizes communication and adaptation components in terms of on distributed locations.We notice that expressing both internal and external exceptional events is useful in practice; for instance, both kinds of events coexist in BPMN 2.0 (see, e.g., [DRMR13,Chap.4]).
Directions for future work include validating our approach in concrete case studies and different settings.We intend to revisit the model of supervision trees (a mechanism for fault-tolerance in Erlang) that we gave in [DP13b].Also, it would be interesting to explore if our approach based on events can be harmonized with the model of security-driven adaptation that have been recently developed in [CDP14], in which read and write violations to security policies determine adaptation events.Finally, it would be worth accommodating existing static techniques for progress (deadlock-freedom) into our typing disciplines for run-time adaptation.We see consistency and progress as orthogonal guarantees; we do not find major obstacles preventing an extension of our typing systems with the existing techniques such as those developed in, e.g., [VV13,PVV14].

Based on the above definitions, we can now define:
Definition A.4 (Coinductive Duality and Subtyping).Let T, S be types.
• The coinductive duality relation, denoted ⊥ C , is defined by T ⊥ C S if and only if there exists a duality relation R such that (T, S) ∈ R. • The coinductive subtyping relation, denoted ≤ C , is defined by T ≤ C S if and only if there exists a type simulation S such that (T, S) ∈ S. The extension of ≤ C to typings, written ∆ ≤ C ∆ , arises as expected.

B.1. Binary Case
The following auxiliary result concerns substitutions for channels, expressions, and process variables.Observe how the case of process variables has been relaxed so as to allow substitution with a process with "smaller" interface (in the sense of , cf.Definition 4.2).This extra flexibility is in line with the typing rule for located processes (cf.Rule t:Loc , Table 3), and will be useful later on in proofs.
Lemma B.1 (Substitution Lemma).As reduction may occur inside contexts, in proofs it is useful to have typed contexts.These are contexts in which the hole has associated typing information-concretely, the typing for processes which may fill in the hole.Defining context requires a simple extension of judgments, in the following way: Axiom t:Hole allows us to introduce typed holes into contexts.In Rule t:Fill , P is a process (it does not have any holes), and C is a context with a hole of type Γ; Θ ∆; I.The substitution of occurrences of • in C with P , noted C{P }, is sound as long as the typings of P coincide with those declared in H for C. We introduce some convenient notation for typed holes.Proof.By induction on the last rule applied in the reduction.We assume that e ↓ c is a type preserving operation, for every e.We examine only a few interesting cases, namely those for session establishment, runtime update, and intra-session communication; remaining cases are similar or simpler.
for a session type α; − location queues, denoted loc r ; and − adaptation signals, denoted loc(r).

Definition 5 . 7 (
Networks).The syntax of networks N and adaptation requests r is defined as N ::= new(G) initialize global type | loc M[ [P ] ]; P; loc r active location | loc P; loc r inactive location | κ : h message queue | κ e h internal adaptation: event queue | (νκ)N restriction | N | N parallel composition r ::= empty request | (add : Q, T ) external adaptation: upgrade request

e true if e then P 1 else P 2 τ− → P 1 M:P:IfF e false if e then P 1 else P 2 τ− → P 2 M
[ µX .P /X]

Proof.
Easily shown by induction on the structure of P .

H
; Γ ; Θ C ∆; I Intuitively, H contains the description of the type associated to the hole in C. Typing rules are extended in the expected way.Because contexts have a single hole, H is either empty of has exactly one element.When H is empty, we write Γ ; Θ P ∆; I instead of • ; Γ ; Θ P ∆; I. Two additional typing rules are required: t:Hole • Γ;Θ ∆;I ; Γ ; Θ • ∆; I t:Fill • Γ;Θ ∆;I ; Γ ; Θ C ∆ 1 ; I 1 Γ ; Θ P ∆; I Γ ; Θ C{P } ∆ 1 ; I 1

Notation B. 2 .
Let us use S, S , . . . to range over judgments attached to typed holes.This way, • S denotes the valid typed hole associated to S = Γ; Θ ∆; I. Lemma B.3.Let P and C be a process and a typed context such that Γ ; Θ C{P } ∆; I is a derivable judgment.There exist ∆ 1 , I 1 such that (i) Γ ; Θ P ∆ 1 ; I 1 is a well-typed process, and (ii) ∆ 1 ⊆ ∆ and I 1 I. Lemma B.4.Let C be a context.Suppose • S ; Γ ; Θ C ∆ C ∪ ∆ S ; I C I S with S = Γ; Θ ∆ S ; I S is well-typed.Let S = Γ; Θ ∆ S ; I S .Then • S ; Γ ; Θ C ∆ C ∪ ∆ S ; I C I S is a derivable judgment.Theorem B.5 (Subject Congruence).If Γ ; Θ P ∆; I and P ≡ Q then Γ ; Θ Q ∆; I.Proof.By induction on the derivation of P ≡ Q, with a case analysis on the last applied rule.